Leetcode Top Interview ✨
GithubLinkedinXOfficial Website
  • Leetcode Top Interview 🎯
  • Guide to Calculating Algorithm Complexity 🚀
  • Topic 1 Array - String
    • 88. Merge Sorted Arrays 🧩
    • 27. Remove Element 🧹
    • 26. Remove Duplicates from Sorted Array 🚫
    • 80. Remove Duplicates from Sorted Array II 🚫🚫
    • 169. Majority Element 👑
    • 189. Rotate Array 🔄
    • 121. Best Time to Buy and Sell Stock 📈
    • 122. Best Time to Buy and Sell Stock II 📈💰
    • 55. Jump Game 🏃‍♂️
    • 45. Jump Game II 🏃‍♂️
    • 274. H-Index 📊
    • 380. Insert Delete GetRandom O(1) 🎲
    • 238. Product of Array Except Self 🔄
    • 134. Gas Station ⛽
    • 135. Candy 🍬
    • 42. Trapping Rain Water 🌧️
    • 13. Roman to Integer 🔢
    • 018 Integer to Roman
    • 58. Length of Last Word 🔠
    • 14. Longest Common Prefix 🌱
    • 151. Reverse Words in a String 🔄
    • 6. Zigzag Conversion 🔀
    • 28. Find the Index of the First Occurrence in a String 🔄
    • 68. Text Justification 🔄
  • Topic 2 Two Pointers
    • 125. Valid Palindrome 🚦
    • 392. Is Subsequence 📏
    • 167. Two Sum II - Input Array Is Sorted 🔍
    • 11. Container With Most Water 🏞️
    • 15. 3Sum 🌐
  • Topic 3 Sliding Window
    • 209. Minimum Size Subarray Sum 🌐
    • 3. Longest Substring Without Repeating Characters 🌐
    • 30. Substring with Concatenation of All Words 🌐
    • 76. Minimum Window Substring 🌐
  • Topic 4 Matrix
    • 36. Valid Sudoku 🌐
    • 54. Spiral Matrix 🌐
    • 48. Rotate Image 🔄
    • 73. Set Matrix Zeroes
    • 289. Game of Life 🖼️
  • Topic 5 Hashmap
    • 383. Ransom Note 🔍
    • 205. Isomorphic Strings 🔍
    • 290. Word Pattern 🧩
    • 242. Valid Anagram 🎢
    • 49. Group Anagrams 🤹‍♂️
    • 1. Two Sum 🔍
    • 202. Happy Number 🤩
    • 219. Contains Duplicate II 🔍
    • 128. Longest Consecutive Sequence 🔍
  • Topic 6 Intervals
    • 228. Summary Ranges 📊
    • 56. Merge Intervals 🔀
    • 57. Insert Interval 🆕
    • 452. Minimum Number of Arrows to Burst Balloons 🎈
  • Topic 7 Stack
    • 20. Valid Parentheses 🔍
    • 71. Simplify Path 🗺️
    • 155. Min Stack 🗃️
    • 150. Evaluate Reverse Polish Notation 🧠💻
    • 224. Basic Calculator 🧮
  • Topic 8 Linked List
    • 141. Linked List Cycle 🔁
    • 2. Add Two Numbers 🔢
    • 21. Merge Two Sorted Lists 🔗
    • 138. Copy List with Random Pointer 🔗
    • 92. Reverse Linked List II 🔄
      • Let’s explain step by step 🐇
    • 25. Reverse Nodes in k-Group 🔄
    • 19. Remove Nth Node From End of List 🗑️
    • 82. Remove Duplicates from Sorted List II ❌🔢
    • 61. Rotate List 🔄
    • 86. Partition List 🔗
    • 146. LRU Cache 🔗
  • Topic 9 Binary Tree General
    • 104. Maximum Depth of Binary Tree 🔗
    • 100. Same Tree 🔗
    • 226. Invert Binary Tree 🔗
    • 101. Symmetric Tree 🔗
    • 105. Construct Binary Tree from Preorder and Inorder Traversal 🔗
    • 106. Construct Binary Tree from Inorder and Postorder Traversal 🔗
    • 117. Populating Next Right Pointers in Each Node II 🔗
    • 114. Flatten Binary Tree to Linked List 🔗
    • 112. Path Sum 🔗
    • 129. Sum Root to Leaf Numbers 🔗
      • What_is_DFS
    • 124. Binary Tree Maximum Path Sum 🔗
Powered by GitBook
On this page
  • Problem Statement 📜
  • Examples 🌟
  • Constraints ⚙️
  • Solution 💡
  • Java Solution
  • Explanation of the Solution
  • Time Complexity ⏳
  • Space Complexity 💾

Was this helpful?

  1. Topic 7 Stack

20. Valid Parentheses 🔍

PreviousTopic 7 StackNext71. Simplify Path 🗺️

Last updated 4 months ago

Was this helpful?

Difficulty: Easy - Tags: Stack, String


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:

s = "()[]{}"

Output:

true

🔹 Example 3:

Input:

s = "(]"

Output:

false

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

import java.util.Stack;

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();

        // Step 1: Iterate through the characters of the string
        for (char c : s.toCharArray()) {
            // Step 2: Push opening brackets onto the stack
            if (c == '(' || c == '{' || c == '[') {
                stack.push(c);
            }
            // Step 3: Check for matching closing brackets
            else {
                if (stack.isEmpty()) return false;
                char top = stack.pop();
                if ((c == ')' && top != '(') ||
                    (c == '}' && top != '{') ||
                    (c == ']' && top != '[')) {
                    return false;
                }
            }
        }

        // Step 4: Ensure the stack is empty
        return stack.isEmpty();
    }
}

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 .

LeetCode Problem Link
here