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.

Input: s = "()"
Output: true
Input: s = "()[]{}"
Output: true
Input: s = "(]"
Output: true
Constraints:

Contents

In this approach, we are going to use a Stack datastructure to store opening brackets, and when a closing bracket occurred, we will check the corresponding opening bracket and check they are the correct pair, if they are not then return false, otherwise continue checking and at the end check if the stack has any unbalanced entries, return true if it is empty, false otherwise.

Implementation steps:
package io.cscode.algorithms.stack; import java.util.Map; import java.util.Stack; public class ValidParentheses { static boolean isValid(String s) { Stack<Character> chars = new Stack<>(); Map<Character, Character> closeToOpenMap = Map.of(')', '(', ']','[','}','{'); for(char c : s.toCharArray()) { if(closeToOpenMap.containsKey(c)) { if(!chars.isEmpty() && closeToOpenMap.get(c).equals(chars.peek())) { chars.pop(); } else { return false; } } else { chars.push(c); } } return chars.isEmpty(); } public static void main(String[] args) { System.out.println(isValid("()")); System.out.println(isValid(")(")); System.out.println(isValid("(]")); System.out.println(isValid(")")); } }
Complexity Analysis:

Time complexity: Above code runs in O(n) time where n is the length of input string s.
Space complexity: O(n), since we are storing opening brackets into a Stack.

Above implementations source code can be found at GitHub link for Java code