Validating Brackets with Stack and HashMap

Day - 73 Valid Parentheses The problem - Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. A string is valid if: open brackets are closed by the same type of brackets, open brackets are closed in the correct order, and every close bracket has a corresponding open bracket. Brute Force - Repeatedly scan the string and remove valid pairs like "()", "{}", "[]" until no more pairs can be removed. If the string becomes empty, it's valid. This gives O(n²) time complexity due to multiple passes and string manipulation. Approach Used - •) Create a Stack<Character> to track opening brackets •) Create a HashMap<Character, Character> to map closing to opening brackets, ')' → '(' , '}' → '{' and ']' → ‘[‘. •) Process each character, Iterate through each character c in the string, 1 - If c is an opening bracket, push it onto the stack. 2 - If c is a closing bracket, - Check if stack is empty, return false. - ⁠Pop from stack and check if it matches mapping.get(c), if mismatch → return false. •) Final Validation, 1 - After processing all characters, check if stack is empty. 2 - Empty stack means all brackets matched correctly. 3 - Non-empty stack means unmatched opening brackets remain. Complexity - Time - O(n), single pass through the string, each character processed once and stack operations (push/pop) are O(1). Space - O(n), stack can hold up to n/2 opening brackets in worst case. Note - Stack naturally handles nested structures with LIFO (Last-In-First-Out) behavior. Each closing bracket must match the most recent unmatched opening bracket. HashMap enables O(1) lookup for matching pairs, making validation efficient. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving

  • text

To view or add a comment, sign in

Explore content categories