๐Ÿ“˜Day 6 โ€“ Teacher's Day Challenge | Valid Parentheses | Stack + Hash Map

TanishiTanishi
2 min read

๐Ÿ—“๏ธ Date: July 30, 2025

๐Ÿ“Œ Challenge:
๐Ÿ”ข Problem: Valid Parentheses โ€“ LeetCode #20 (Easy)
๐ŸŽฏ Topic: Stack, Hash Map, String

๐Ÿ’ป Platform: Leetcode


๐Ÿ”— Table of Contents


โœ… Problem Statement (Summary):
Check if a given string of parentheses ()[]{} is valid. A string is valid if:

  • Open brackets are closed by the same type.

  • Brackets are closed in the correct order.

  • Every closing bracket has a matching opening bracket.

๐Ÿงพ Examples:

  • "()" โ†’ true

  • "()[]{}" โ†’ true

  • "(]" โ†’ false

  • "([])" โ†’ true

  • "([)]" โ†’ false


๐Ÿง  What I Learned Today:

  • Use a stack to keep track of open brackets.

  • Use a hash map to match closing โ†’ opening brackets.

  • Push when open bracket, check+pop when closing.

  • Edge case: stack must be empty at end for a valid string.


๐Ÿงช Code (C++):

class Solution {
public:
    bool isValid(string s) {
        unordered_map<char, char> pairs = {
            {')', '('}, {']', '['}, {'}', '{'}
        };
        stack<char> st;
        for (char ch : s) {
            if (ch == '(' || ch == '{' || ch == '[') {
                st.push(ch);
            } else {
                if (st.empty() || st.top() != pairs[ch]) {
                    return false;
                }
                st.pop();
            }
        }
        return st.empty();
    }
};

๐Ÿ•’ Time Complexity: O(n)
๐Ÿ“ฆ Space Complexity: O(n)


๐Ÿ“ธ LeetCode Submission Screenshot:


โœ… Key Takeaways:

  • Stack is ideal for tracking nested or matching structures.

  • HashMap simplifies pairing and matching logic.

  • Final check on stack.empty() ensures no unmatched opens remain.


๐Ÿ“ˆ Daily Summary

MetricValue
Problems Solved1
Topics CoveredStack, Matching Brackets
Tools UsedC++
Next FocusStack + Queue Pattern Problems
Day6 / 30

๐Ÿ—‚๏ธ Tags:
#leetcode #43DaysChallenge #stack #hashmap #dsa #cpp #validparentheses

0
Subscribe to my newsletter

Read articles from Tanishi directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Tanishi
Tanishi