What is the main idea behind using a stack to check for balanced parentheses?
Use a stack to keep track of opening parentheses. For every closing parenthesis, check if it matches the last opening one on the stack. If all match and stack is empty at the end, parentheses are balanced.
Click to reveal answer
beginner
Which characters are typically considered in the balanced parentheses problem?
The characters are usually '(', ')', '{', '}', '[' and ']'. Each opening bracket must be matched with the correct closing bracket.
Click to reveal answer
beginner
What happens if a closing parenthesis does not match the top of the stack?
It means the parentheses are not balanced. The algorithm should stop and return false immediately.
Click to reveal answer
beginner
Why must the stack be empty at the end of the check for balanced parentheses?
If the stack is not empty, it means there are unmatched opening parentheses left, so the parentheses are not balanced.
Click to reveal answer
beginner
In Rust, which data structure is commonly used to implement a stack for this problem?
A Vec<char> is commonly used as a stack in Rust because it supports push and pop operations efficiently.
Click to reveal answer
What should you do when you encounter an opening parenthesis in the string?
APop from the stack
BReturn false immediately
CIgnore it
DPush it onto the stack
✗ Incorrect
Opening parentheses are pushed onto the stack to be matched later.
If the stack is empty but you find a closing parenthesis, what does it mean?
AThere is an unmatched closing parenthesis
BIgnore the closing parenthesis
CParentheses are balanced
DPush the closing parenthesis onto the stack
✗ Incorrect
A closing parenthesis without a matching opening one means unbalanced parentheses.
Which Rust method removes the last element from a Vec used as a stack?
Apush()
Bpop()
Cremove()
Dinsert()
✗ Incorrect
pop() removes and returns the last element from the Vec.
What is the time complexity of checking balanced parentheses using a stack?
AO(n)
BO(n^2)
CO(log n)
DO(1)
✗ Incorrect
Each character is processed once, so the time complexity is linear, O(n).
What should the function return if all parentheses are matched and stack is empty at the end?
Anull
Bfalse
Ctrue
Dstack size
✗ Incorrect
True means the parentheses are balanced.
Explain step-by-step how a stack helps to check if parentheses in a string are balanced.
Think about matching pairs and last-in-first-out order.
You got /4 concepts.
Describe how you would implement balanced parentheses check in Rust using Vec as a stack.
Use Vec<char> with push and pop methods.
You got /5 concepts.
Practice
(1/5)
1. What is the main purpose of using a stack in the Balanced Parentheses Problem?
easy
A. To keep track of opening parentheses and match them with closing ones
B. To count the total number of parentheses in the string
C. To reverse the order of parentheses in the string
D. To sort the parentheses alphabetically
Solution
Step 1: Understand the role of stack in parentheses matching
A stack stores opening parentheses as they appear to check if each closing parenthesis matches the last opened one.
Step 2: Explain why other options are incorrect
Counting, reversing, or sorting parentheses does not help in checking if they are balanced.
Final Answer:
To keep track of opening parentheses and match them with closing ones -> Option A
Quick Check:
Stack tracks openings for matching = B [OK]
Hint: Stack stores openings to match closings quickly [OK]
Common Mistakes:
Thinking stack counts parentheses instead of matching
Confusing stack with queue for this problem
Assuming stack sorts parentheses
2. Which of the following Rust code snippets correctly pushes an opening parenthesis '(' onto a stack named stack?
easy
A. stack.insert('(');
B. stack.push('(');
C. stack.add('(');
D. stack.append('(');
Solution
Step 1: Recall Rust Vec method to add elements
In Rust, Vec uses push() to add elements at the end.
Step 2: Verify other methods are invalid for Vec
add(), insert() require different parameters or do not exist; append() merges vectors, not single elements.
Final Answer:
stack.push('('); -> Option B
Quick Check:
Vec push method = push() [OK]
Hint: Use push() to add items to Rust Vec stack [OK]
Common Mistakes:
Using append() to add single element
Confusing insert() with push()
Using add() which is not a Vec method
3. What will be the output of the following Rust code snippet that checks if parentheses are balanced?
fn is_balanced(s: &str) -> bool {
let mut stack = Vec::new();
for ch in s.chars() {
if ch == '(' {
stack.push(ch);
} else if ch == ')' {
if stack.pop().is_none() {
return false;
}
}
}
stack.is_empty()
}
fn main() {
println!("{}", is_balanced("(()())"));
}
medium
A. false
B. Runtime panic
C. Compilation error
D. true
Solution
Step 1: Trace the input string "(()())" character by character
Process '(', push ['(']; '(', push ['(','(']; ')', pop ['(']; '(', push ['(','(']; ')', pop ['(']; ')', pop []. All match.
Step 2: Check final stack state
Stack is NOT empty after processing all 6 characters because the input string "(()())" has 6 characters but the last character is ')', so the stack ends empty. Wait, let's count carefully: Characters: '(' push ['('] '(' push ['(','('] ')' pop ['('] '(' push ['(','('] ')' pop ['('] ')' pop [] Stack is empty after processing all characters, so stack.is_empty() returns true.
Final Answer:
true -> Option D
Quick Check:
Matched pairs and empty stack = true [OK]
Hint: Count openings and closings; unmatched means false [OK]
Common Mistakes:
Mis-counting the number of parentheses
Ignoring stack emptiness at end
Confusing pop() returning None with Some
4. Identify the bug in this Rust function that checks balanced parentheses:
fn check_balance(s: &str) -> bool {
let mut stack = Vec::new();
for ch in s.chars() {
if ch == '(' {
stack.push(ch);
} else if ch == ')' {
stack.pop();
}
}
stack.is_empty()
}
medium
A. It uses a wrong data structure instead of Vec
B. It pushes closing parentheses instead of opening
C. It does not check if pop() returns None before popping
D. It returns true even if stack is not empty
Solution
Step 1: Analyze pop() usage on empty stack
The function calls stack.pop() without checking if stack is empty, so popping from empty stack returns None but is ignored.
Step 2: Explain consequence of missing check
This causes false positives when closing parentheses appear without matching openings, as function never returns false early.
Final Answer:
It does not check if pop() returns None before popping -> Option C
Quick Check:
Missing pop() None check causes errors [OK]
Hint: Always check pop() result before proceeding [OK]
Common Mistakes:
Ignoring pop() returning None on empty stack
Pushing wrong characters
Assuming stack emptiness check is enough
5. Given the Rust function below, what will be the output when checking the string "{[(())]}"? The function supports '()', '[]', and '{}' pairs.
fn is_balanced(s: &str) -> bool {
let mut stack = Vec::new();
for ch in s.chars() {
if ch == '(' || ch == '[' || ch == '{' {
stack.push(ch);
} else {
if let Some(top) = stack.pop() {
if (ch == ')' && top != '(') ||
(ch == ']' && top != '[') ||
(ch == '}' && top != '{') {
return false;
}
} else {
return false;
}
}
}
stack.is_empty()
}
fn main() {
println!("{}", is_balanced("{[(())]}"));
}
hard
A. true
B. false
C. Compilation error
D. Runtime panic
Solution
Step 1: Trace the string "{[(())]}" step-by-step
Push '{', '[', '(', '('. Then pop for ')', ')', ']', '}'. Each closing matches the last opening correctly.
Step 2: Check stack emptiness after processing
All pairs matched, stack is empty, so function returns true.
Final Answer:
true -> Option A
Quick Check:
All pairs matched and stack empty = true [OK]
Hint: Match each closing with last opening in stack [OK]
Common Mistakes:
Not handling multiple bracket types
Ignoring order of matching pairs
Forgetting to check stack empty at end
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.