Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to push an opening parenthesis onto the stack.
DSA Rust
if ch == '(' { stack.[1](ch); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop instead of push will remove an element instead of adding.
Using peek only looks at the top element without adding.
✗ Incorrect
To add an element to the stack, we use the push method.
2fill in blank
mediumComplete the code to check if the stack is empty before popping.
DSA Rust
if !stack.[1]() { stack.pop(); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using is_full will not tell if the stack is empty.
Using len returns the number of elements but is not a boolean check.
✗ Incorrect
We check if the stack is empty using is_empty() before popping to avoid errors.
3fill in blank
hardFix the error in matching the popped character with the current closing parenthesis.
DSA Rust
if let Some(top) = stack.pop() { if top != [1] { return false; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing with the closing parenthesis itself causes logic errors.
Using '[' or '{' does not match the ')' character.
✗ Incorrect
For a closing parenthesis ')', the matching opening is '('. We compare with '('.
4fill in blank
hardFill both blanks to correctly match closing brackets with their opening counterparts.
DSA Rust
let matching = match ch {
')' => [1],
']' => [2],
_ => ' ',
};Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up different types of brackets.
Using closing brackets instead of opening ones.
✗ Incorrect
')' matches '(', and ']' matches '['. These are the correct pairs.
5fill in blank
hardFill all three blanks to complete the function that checks balanced parentheses.
DSA Rust
fn is_balanced(s: &str) -> bool {
let mut stack = Vec::new();
for ch in s.chars() {
if ch == [1] || ch == [2] || ch == [3] {
stack.push(ch);
} else if ch == ')' || ch == ']' || ch == '}' {
if stack.is_empty() {
return false;
}
let top = stack.pop().unwrap();
let matching = match ch {
')' => '(',
']' => '[',
'}' => '{',
_ => ' ',
};
if top != matching {
return false;
}
}
}
stack.is_empty()
}Attempts:
3 left
💡 Hint
Common Mistakes
Including invalid characters like '<'.
Missing one or more opening bracket types.
✗ Incorrect
The opening brackets are '(', '[', and '{'. These are pushed onto the stack.
