Bird
Raised Fist0
DSA C#programming~20 mins

Balanced Parentheses Problem Using Stack in DSA C# - 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 C# code that checks if the parentheses in the string are balanced?
DSA C#
using System;
using System.Collections.Generic;

class Program {
    static bool IsBalanced(string s) {
        Stack<char> stack = new Stack<char>();
        foreach (char c in s) {
            if (c == '(') {
                stack.Push(c);
            } else if (c == ')') {
                if (stack.Count == 0) return false;
                stack.Pop();
            }
        }
        return stack.Count == 0;
    }

    static void Main() {
        string input = "(()())";
        Console.WriteLine(IsBalanced(input));
    }
}
ACompilation error
BFalse
CRuntime exception
DTrue
Attempts:
2 left
💡 Hint
Think about how the stack is used to track opening parentheses and matched with closing ones.
❓ Predict Output
intermediate
2:00remaining
Output for Unbalanced Parentheses Input
What will the output be when the following code runs with input string "(()"?
DSA C#
using System;
using System.Collections.Generic;

class Program {
    static bool IsBalanced(string s) {
        Stack<char> stack = new Stack<char>();
        foreach (char c in s) {
            if (c == '(') {
                stack.Push(c);
            } else if (c == ')') {
                if (stack.Count == 0) return false;
                stack.Pop();
            }
        }
        return stack.Count == 0;
    }

    static void Main() {
        string input = "(()";
        Console.WriteLine(IsBalanced(input));
    }
}
ATrue
BFalse
CCompilation error
DRuntime exception
Attempts:
2 left
💡 Hint
Check if all opening parentheses have matching closing ones.
🧠 Conceptual
advanced
1:30remaining
Why Use a Stack for Balanced Parentheses?
Why is a stack the best data structure to check for balanced parentheses in a string?
ABecause a stack allows random access to any element
BBecause a stack stores all characters in sorted order
CBecause a stack follows Last-In-First-Out order which matches how parentheses are nested
DBecause a stack automatically counts the number of parentheses
Attempts:
2 left
💡 Hint
Think about how parentheses open and close in nested order.
🔧 Debug
advanced
2:00remaining
Identify the Bug in Parentheses Checking Code
What error will this code produce when checking the string ")("?
DSA C#
using System;
using System.Collections.Generic;

class Program {
    static bool IsBalanced(string s) {
        Stack<char> stack = new Stack<char>();
        foreach (char c in s) {
            if (c == '(') {
                stack.Push(c);
            } else if (c == ')') {
                stack.Pop();
            }
        }
        return stack.Count == 0;
    }

    static void Main() {
        string input = ")(";
        Console.WriteLine(IsBalanced(input));
    }
}
AInvalidOperationException due to popping from empty stack
BReturns True
CReturns False
DCompilation error
Attempts:
2 left
💡 Hint
What happens if you pop from an empty stack?
🚀 Application
expert
2:30remaining
Balanced Parentheses with Multiple Types
Given the code below that checks for balanced parentheses, brackets, and braces, what is the output for input "{[(])}"?
DSA C#
using System;
using System.Collections.Generic;

class Program {
    static bool IsBalanced(string s) {
        Stack<char> stack = new Stack<char>();
        foreach (char c in s) {
            if (c == '(' || c == '[' || c == '{') {
                stack.Push(c);
            } else {
                if (stack.Count == 0) return false;
                char top = stack.Pop();
                if ((c == ')' && top != '(') ||
                    (c == ']' && top != '[') ||
                    (c == '}' && top != '{')) {
                    return false;
                }
            }
        }
        return stack.Count == 0;
    }

    static void Main() {
        string input = "{[(])}";
        Console.WriteLine(IsBalanced(input));
    }
}
AFalse
BRuntime exception
CCompilation error
DTrue
Attempts:
2 left
💡 Hint
Check if the closing brackets match the last opening bracket.

Practice

(1/5)
1. What is the main purpose of using a stack in the Balanced Parentheses Problem?
easy
A. To count the total number of parentheses in the string
B. To keep track of opening parentheses and match them with closing ones
C. To reverse the order of parentheses in the string
D. To sort the parentheses based on their type

Solution

  1. Step 1: Understand the role of stack in parentheses matching

    A stack helps keep track of opening parentheses so that each closing parenthesis can be matched correctly in order.
  2. Step 2: Identify why other options are incorrect

    Counting or reversing parentheses does not solve the matching problem, and sorting is unrelated to balance checking.
  3. Final Answer:

    To keep track of opening parentheses and match them with closing ones -> Option B
  4. Quick Check:

    Stack tracks openings for matching closings [OK]
Hint: Stack stores openings to match closings in order [OK]
Common Mistakes:
  • Thinking stack counts parentheses instead of matching
  • Confusing stack with queue for this problem
  • Assuming stack reverses parentheses order
2. Which of the following C# code snippets correctly pushes an opening parenthesis onto a stack named stack?
easy
A. stack.Push('(');
B. stack.Add('(');
C. stack.Insert('(');
D. stack.Enqueue('(');

Solution

  1. Step 1: Recall stack method to add elements

    In C#, the method to add an element to a stack is Push().
  2. Step 2: Identify incorrect methods

    Add() and Insert() are not stack methods; Enqueue() is for queues.
  3. Final Answer:

    stack.Push('('); -> Option A
  4. Quick Check:

    Use Push() to add to stack [OK]
Hint: Use Push() to add elements to stack in C# [OK]
Common Mistakes:
  • Using queue methods like Enqueue() on stack
  • Trying to use Add() or Insert() which don't exist for stack
  • Confusing stack with list methods
3. What will be the output of the following C# code snippet?
string input = "({[]})";
Stack<char> stack = new Stack<char>();
foreach (char c in input) {
  if (c == '(' || c == '{' || c == '[') {
    stack.Push(c);
  } else {
    if (stack.Count == 0) {
      Console.WriteLine("Unbalanced");
      return;
    }
    char top = stack.Pop();
    if ((c == ')' && top != '(') || (c == '}' && top != '{') || (c == ']' && top != '[')) {
      Console.WriteLine("Unbalanced");
      return;
    }
  }
}
if (stack.Count == 0) Console.WriteLine("Balanced"); else Console.WriteLine("Unbalanced");
medium
A. Runtime Error
B. Unbalanced
C. No Output
D. Balanced

Solution

  1. Step 1: Trace the input string character by character

    Opening brackets '(', '{', '[' are pushed onto the stack. Closing brackets pop and check matching. The input "({[]})" is perfectly nested.
  2. Step 2: Check stack emptiness after processing

    After processing all characters, stack is empty, so output is "Balanced".
  3. Final Answer:

    Balanced -> Option D
  4. Quick Check:

    All pairs matched, stack empty = Balanced [OK]
Hint: Match each closing with last opening using stack [OK]
Common Mistakes:
  • Not checking stack empty before popping
  • Mismatching bracket pairs
  • Ignoring stack emptiness at end
4. Identify the bug in the following C# code snippet for checking balanced parentheses:
Stack<char> stack = new Stack<char>();
foreach (char c in input) {
  if (c == '(' || c == '{' || c == '[') {
    stack.Push(c);
  } else {
    char top = stack.Pop();
    if ((c == ')' && top != '(') || (c == '}' && top != '{') || (c == ']' && top != '[')) {
      return false;
    }
  }
}
return stack.Count == 0;
medium
A. Not returning true when balanced
B. Incorrect matching of parentheses pairs
C. Missing check if stack is empty before Pop()
D. Using stack.Push() instead of Pop() for closing brackets

Solution

  1. Step 1: Check for stack underflow before popping

    The code pops from stack without checking if it's empty, which can cause runtime error if closing bracket appears first.
  2. Step 2: Confirm matching logic is correct

    Matching pairs are correctly checked, and return false if mismatch occurs.
  3. Final Answer:

    Missing check if stack is empty before Pop() -> Option C
  4. Quick Check:

    Always check stack empty before Pop() [OK]
Hint: Check stack empty before Pop() to avoid errors [OK]
Common Mistakes:
  • Popping from empty stack causing exceptions
  • Ignoring stack.Count == 0 before Pop()
  • Confusing Push and Pop methods
5. Given the string "[{()}]({[]})", which of the following modifications to the balanced parentheses algorithm will correctly handle this input and return true?

Options:
A) Ignore all characters except parentheses.
B) Use a stack and match pairs as usual.
C) Use two stacks, one for opening and one for closing parentheses.
D) Use a queue instead of a stack to track parentheses.
hard
A. Use a stack and match pairs as usual.
B. Ignore all characters except parentheses.
C. Use two stacks, one for opening and one for closing parentheses.
D. Use a queue instead of a stack to track parentheses.

Solution

  1. Step 1: Understand the input and algorithm

    The input contains only parentheses characters. The standard stack-based matching algorithm works for nested and sequential pairs.
  2. Step 2: Evaluate each option's correctness

    Use a stack and match pairs as usual. is correct as it uses the standard stack approach. Ignore all characters except parentheses. is irrelevant since input has only parentheses. Use two stacks, one for opening and one for closing parentheses. complicates unnecessarily. Use a queue instead of a stack to track parentheses. fails because queue does not track last opening bracket.
  3. Final Answer:

    Use a stack and match pairs as usual. -> Option A
  4. Quick Check:

    Standard stack method handles nested pairs [OK]
Hint: Standard stack method works for all balanced parentheses [OK]
Common Mistakes:
  • Trying to use queue which breaks matching order
  • Overcomplicating with multiple stacks
  • Ignoring characters that are not parentheses
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