20. Valid Parentheses ๐Ÿ”

Difficulty: Easy - Tags: Stack, String

LeetCode Problem Link


Problem Statement ๐Ÿ“œ

Given a string s containing just the characters '(', ')', '{', '}', '[', and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.

  2. Open brackets must be closed in the correct order.

  3. Every close bracket has a corresponding open bracket of the same type.


Examples ๐ŸŒŸ

๐Ÿ”น Example 1:

Input:

s = "()"

Output:

true

๐Ÿ”น Example 2:

Input:

Output:


๐Ÿ”น Example 3:

Input:

Output:


Constraints โš™๏ธ

  • 1 <= s.length <= 10^4

  • s consists of parentheses only '()[]{}'.


Solution ๐Ÿ’ก

The problem can be solved using a stack:

  1. Push opening brackets ((, {, [) onto the stack.

  2. When encountering a closing bracket (), }, ]):

    • Check if the stack is not empty and if the top of the stack matches the closing bracket. If it matches, pop the stack.

    • Otherwise, the string is invalid.

  3. At the end, the stack must be empty for the string to be valid.


Java Solution


Explanation of the Solution

  1. Stack Usage:

    • A stack is used to track unmatched opening brackets.

    • Opening brackets are pushed onto the stack, and closing brackets attempt to match the top of the stack.

  2. Validation:

    • If the stack is empty before encountering a closing bracket or the top of the stack doesn't match the closing bracket, the string is invalid.

  3. Final Check:

    • At the end of the traversal, the stack should be empty for the string to be valid.


Time Complexity โณ

  • O(n): Each character is processed once, and stack operations (push/pop) are O(1).

Space Complexity ๐Ÿ’พ

  • O(n): In the worst case, all characters could be pushed onto the stack (e.g., all opening brackets).

You can find the full solution here.

Last updated

Was this helpful?