Tutorialspoint
Problem
Solution
Submissions

Valid Parentheses

Certification: Basic Level Accuracy: 49.23% Submissions: 65 Points: 5

Write a Java program to implement the isValid(String s) function, which determines if an input string containing just the characters '(', ')', '{', '}', '[' and ']' is valid.

Example 1
  • Input: s = "()"
  • Output: true
  • Explanation:
    • Push '(' → Stack = ['(']
    • Encounter ')' → Matches top, pop '('
    • Stack is empty → valid
Example 2
  • Input: s = "([)]"
  • Output: false
  • Explanation:
    • Push '(' → Push '['
    • ')' does not match top '[' → invalid
Constraints
  • 1 ≤ s.length ≤ 10^4
  • s consists of parentheses only '()[]{}'
  • Time Complexity: O(n)
  • Space Complexity: O(n)
StringsStackCapgeminiLTIMindtree
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a stack to keep track of opening brackets
  • When you encounter an opening bracket, push it onto the stack
  • When you encounter a closing bracket, check if the stack is empty or if the top element is the corresponding opening bracket
  • If the stack is not empty at the end, the string is invalid

Steps to solve by this approach:

 Step 1: Create a stack to store opening brackets.
 Step 2: Iterate through each character in the string.
 Step 3: If the character is an opening bracket ('(', '[', '{'), push it onto the stack.
 Step 4: If the character is a closing bracket (')', ']', '}'), check if the stack is empty.
 Step 5: If stack is not empty, pop the top element and verify it matches the current closing bracket.
 Step 6: If no match or stack is empty, return false.
 Step 7: After processing all characters, return true if stack is empty, false otherwise.

Submitted Code :