Easy String Problems Java

Valid Parentheses in Java Using Stack

Check whether a string of brackets is correctly opened and closed.

  • TimeO(n)
  • SpaceO(n)
  • Hints3
  • Read2 min
Quick answer

Go through the string one character at a time. For each opening bracket, push the closing bracket you expect onto a stack. For each closing bracket, pop the stack and check that it is the same. The string is valid if every check passes and the stack is empty at the end. This takes O(n) time.

StackMatching pairsDeque
1

Problem statement

This is the classic valid parentheses Java question. You get a string made only of (, ), [, ], { and }. Return true if:

  • every opening bracket is closed by the same type, and
  • brackets are closed in the right order (the last one opened is closed first).
Input

A string s made only of the six bracket characters.

Output

true if the brackets are valid, otherwise false.

Examples

Example 1
Inputs = {[()]}
Outputtrue

Each closing bracket matches the one opened most recently.

Example 2
Inputs = ([)]
Outputfalse

The ) arrives while [ is still open.

Example 3
Inputs = ((
Outputfalse

Two brackets are never closed.

Constraints

  • 0 <= length of s <= 10^5
  • An empty string counts as valid
2

Think before you code

Reveal the questions to ask yourself first
  • When you meet a closing bracket, which open bracket must it match?
  • Which data structure gives back the most recent item first?
  • What does it mean if items are left over at the end?
3

Hints

Open one at a time — try again after each.
1 Hint 1
The most recently opened bracket must be closed first. That is last in, first out: a stack.
2 Hint 2
Push the closing bracket you expect. Then the check is one simple comparison.
3 Hint 3
Check for an empty stack before you pop, and again after the loop.
4

Approach

Reveal the step-by-step approach
  1. Create an empty stack. Use ArrayDeque: the Java documentation recommends a Deque over the old Stack class.
  2. For each opening bracket, push its matching closing bracket.
  3. For each closing bracket:
    • If the stack is empty, nothing is open. Return false.
    • Pop the stack. If it is not this bracket, return false.
  4. After the loop, return whether the stack is empty.

New to stacks? Start with data structures and algorithms. The collections framework page gives the wider picture of Java collections.

5

Dry run

Walk through the example step by step

Checking {[()]}. The top of the stack is on the left:

char | action                | stack
-----+-----------------------+--------
{    | push }                | }
[    | push ]                | ] }
(    | push )                | ) ] }
)    | pop ), it matches     | ] }
]    | pop ], it matches     | }
}    | pop }, it matches     | empty
end  | stack is empty        | true
6

Solution

Reveal the full Java solution
Solution.java
import java.util.ArrayDeque;
import java.util.Deque;

public class ValidParentheses {
    public static boolean isValid(String s) {
        Deque<Character> stack = new ArrayDeque<>();
        for (char c : s.toCharArray()) {
            if (c == '(') {
                stack.push(')');
            } else if (c == '[') {
                stack.push(']');
            } else if (c == '{') {
                stack.push('}');
            } else if (stack.isEmpty() || stack.pop() != c) {
                return false; // nothing open, or the wrong one is open
            }
        }
        return stack.isEmpty(); // anything left was never closed
    }

    public static void main(String[] args) {
        System.out.println(isValid("{[()]}")); // true
        System.out.println(isValid("([)]"));   // false
        System.out.println(isValid("(("));     // false
    }
}

This is valid parentheses Java using stack. The stack always shows what must be closed next. Pushing the expected closing bracket keeps the valid parentheses Java code short: no lookup table is needed.

stack.pop() != c compares a Character with a char. Java turns the Character into a plain char first, so the values are compared correctly.

Valid parentheses Java without stack

Only one type of bracket: a counter is enough. Add 1 for (, take away 1 for ). It must never go below 0 and must end at 0.

// Only for strings made of ( and )
static boolean isValidRound(String s) {
    int open = 0;
    for (char c : s.toCharArray()) {
        open += (c == '(') ? 1 : -1;
        if (open < 0) return false; // closed before it was opened
    }
    return open == 0;
}

It gives true for (()()) and false for ())(.

All three types: keep removing neighbouring pairs until nothing changes.

// Handles all three types, but slower: O(n^2)
static boolean isValidByRemoving(String s) {
    int before;
    do {
        before = s.length();
        s = s.replace("()", "").replace("[]", "").replace("{}", "");
    } while (s.length() < before);
    return s.isEmpty();
}

This is easy to read but slow on long, deeply nested strings. In an interview, give the valid parentheses Java stack answer first and mention this as another idea. Separate counters for the three types do not work: they would accept ([)].

Practise next

After this valid parentheses program in Java, try reverse a linked list, and read the DSA interview questions. For guided practice, see the Java full stack course.

TimeO(n)
SpaceO(n)
7

Review before the interview

Common mistakes

  • Returning true at the end without checking that the stack is empty. This accepts ((.
  • Calling pop on an empty stack. It throws an exception for input such as ).
  • Only counting brackets. Counts miss wrong order, such as ([)].

Edge cases to test

  • An empty string is valid.
  • A string that starts with a closing bracket is invalid.
  • An odd-length string can never be valid.

Interview follow-ups

  • How would you skip letters and digits inside the string?
  • How would you return the position of the first wrong bracket?
  • How many brackets must be added to make a string valid?

Keep practising

Practising for Java interviews?

CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us