Bird
Raised Fist0
DSA Pythonprogramming~20 mins

Balanced Parentheses Problem Using Stack in DSA Python - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Balanced Parentheses Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Balanced Parentheses Check
What is the output of the following code when checking the string "{[()]}" for balanced parentheses?
DSA Python
def is_balanced(s):
    stack = []
    pairs = {')': '(', ']': '[', '}': '{'}
    for char in s:
        if char in '([{' :
            stack.append(char)
        elif char in ')]}' :
            if not stack or stack.pop() != pairs[char]:
                return False
    return not stack

print(is_balanced("{[()]}") )
ATrue
BFalse
CSyntaxError
DNone
Attempts:
2 left
💡 Hint
Think about how the stack is used to match opening and closing brackets.
❓ Predict Output
intermediate
2:00remaining
Output for Unbalanced Parentheses
What will the function return when checking the string "{[(])}" for balanced parentheses?
DSA Python
def is_balanced(s):
    stack = []
    pairs = {')': '(', ']': '[', '}': '{'}
    for char in s:
        if char in '([{' :
            stack.append(char)
        elif char in ')]}' :
            if not stack or stack.pop() != pairs[char]:
                return False
    return not stack

print(is_balanced("{[(])}") )
AFalse
BNone
CIndexError
DTrue
Attempts:
2 left
💡 Hint
Check if the order of brackets is correct in the string.
🔧 Debug
advanced
2:00remaining
Identify the Error in Parentheses Checking Code
What error will this code produce when run with input ")()[]{}"?
DSA Python
def check_balanced(s):
    stack = []
    pairs = {')': '(', ']': '[', '}': '{'}
    for char in s:
        if char in '([{' :
            stack.append(char)
        elif char in ')]}' :
            if stack.pop() != pairs[char]:
                return False
    return not stack

print(check_balanced(")()[]{}"))
AFalse
BTypeError
CTrue
DIndexError
Attempts:
2 left
💡 Hint
What happens if you pop from an empty stack?
❓ Predict Output
advanced
2:00remaining
Output of Balanced Parentheses with Extra Characters
What is the output of the code when checking the string "a+(b*c)-{d/e}" for balanced parentheses?
DSA Python
def is_balanced(s):
    stack = []
    pairs = {')': '(', ']': '[', '}': '{'}
    for char in s:
        if char in '([{' :
            stack.append(char)
        elif char in ')]}' :
            if not stack or stack.pop() != pairs[char]:
                return False
    return not stack

print(is_balanced("a+(b*c)-{d/e}"))
ASyntaxError
BFalse
CTrue
DNone
Attempts:
2 left
💡 Hint
Ignore characters that are not brackets.
🧠 Conceptual
expert
2:00remaining
Stack Usage in Balanced Parentheses Algorithm
Why is a stack the best data structure to check for balanced parentheses in a string?
ABecause a stack automatically removes all brackets when a closing bracket is found.
BBecause a stack allows checking the most recent opening bracket first, matching the last opened with the first closed.
CBecause a stack stores all brackets and sorts them alphabetically for easy matching.
DBecause a stack can store the count of brackets without tracking their order.
Attempts:
2 left
💡 Hint
Think about the order in which brackets must be matched.

Practice

(1/5)
1. What does the Balanced Parentheses problem using a stack check for in a string?
easy
A. Whether every opening bracket has a matching closing bracket in correct order
B. If the string contains only alphabets
C. If the string length is even
D. Whether the string contains any numbers

Solution

  1. Step 1: Understand the problem goal

    The Balanced Parentheses problem checks if all opening brackets like '(' have a matching closing bracket ')' in the correct order.
  2. Step 2: Role of stack in checking

    A stack helps track opening brackets and ensures each one is closed properly in sequence.
  3. Final Answer:

    Whether every opening bracket has a matching closing bracket in correct order -> Option A
  4. Quick Check:

    Balanced parentheses = matching pairs in order [OK]
Hint: Stack tracks openings; match with closings in order [OK]
Common Mistakes:
  • Thinking it checks string length
  • Confusing with character types
  • Ignoring order of brackets
2. Which of the following is the correct way to push an element 'x' onto a stack named 'stack' in Python?
easy
A. stack.push(x)
B. stack.append(x)
C. stack.add(x)
D. stack.insert(x)

Solution

  1. Step 1: Recall Python list methods for stack

    Python uses list to implement stack; to add an element on top, use append().
  2. Step 2: Check each option

    add() and push() are not list methods; insert() adds at specific index, not top.
  3. Final Answer:

    stack.append(x) -> Option B
  4. Quick Check:

    Use append() to push in Python stack [OK]
Hint: Use append() to push in Python stack [OK]
Common Mistakes:
  • Using push() which is not a Python list method
  • Using add() which is for sets
  • Using insert() without index
3. What will be the output of the following code snippet?
def is_balanced(s):
    stack = []
    for char in s:
        if char == '(': stack.append(char)
        elif char == ')':
            if not stack: return False
            stack.pop()
    return not stack

print(is_balanced('(()())'))
print(is_balanced('(()'))
medium
A. True\nFalse
B. False\nTrue
C. True\nTrue
D. False\nFalse

Solution

  1. Step 1: Trace first input '(()())'

    Push '(' three times, pop ')' three times, stack empty at end, returns True.
  2. Step 2: Trace second input '(()'

    Push '(' twice, one ')' pops one '(', stack not empty at end, returns False.
  3. Final Answer:

    True\nFalse -> Option A
  4. Quick Check:

    Balanced string returns True, unbalanced returns False [OK]
Hint: Empty stack at end means balanced parentheses [OK]
Common Mistakes:
  • Not checking stack empty at end
  • Returning true too early
  • Ignoring unmatched openings
4. Find the error in this code snippet for checking balanced parentheses:
def check_balance(s):
    stack = []
    for ch in s:
        if ch == '(': stack.push(ch)
        elif ch == ')':
            if stack == []: return False
            stack.pop()
    return len(stack) == 0
medium
A. Using '==' to check empty stack is wrong
B. Missing return statement inside the loop
C. stack.push(ch) is invalid; use stack.append(ch) instead
D. pop() should be called before checking stack empty

Solution

  1. Step 1: Identify stack method error

    Python list has no push() method; append() should be used to add elements.
  2. Step 2: Verify other parts

    Return statements and empty checks are correct; pop() after check is correct.
  3. Final Answer:

    stack.push(ch) is invalid; use stack.append(ch) instead -> Option C
  4. Quick Check:

    Use append() to add in Python list stack [OK]
Hint: Use append() not push() for Python list stack [OK]
Common Mistakes:
  • Using push() instead of append()
  • Checking stack emptiness incorrectly
  • Calling pop() without checking stack
5. Given the string s = '{[()()]}', which modification is needed in the balanced parentheses stack algorithm to correctly check this string?
hard
A. Only check for parentheses '()' and ignore other brackets
B. Count total number of brackets without matching pairs
C. Use a queue instead of a stack to check balance
D. Add support for multiple types of brackets and match pairs accordingly

Solution

  1. Step 1: Identify bracket types in string

    The string contains curly braces {}, square brackets [], and parentheses ().
  2. Step 2: Modify algorithm for multiple bracket types

    The stack algorithm must track each opening bracket type and match it with the correct closing bracket type.
  3. Final Answer:

    Add support for multiple types of brackets and match pairs accordingly -> Option D
  4. Quick Check:

    Match bracket types correctly for balanced check [OK]
Hint: Match each opening bracket with its correct closing type [OK]
Common Mistakes:
  • Checking only parentheses and ignoring others
  • Using queue instead of stack
  • Counting brackets without matching
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard