Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a stack struct with a fixed-size array.
DSA Rust
struct Stack {
data: [i32; [1]],
top: usize,
}Attempts:
3 left
💡 Hint
Common Mistakes
Using zero size for the array which makes the stack unusable.
Choosing a very large size unnecessarily.
✗ Incorrect
The stack is declared with a fixed size of 5 elements in the array.
2fill in blank
mediumComplete the push method to add an element to the stack.
DSA Rust
impl Stack {
fn push(&mut self, value: i32) {
if self.top < self.data.len() {
self.data[self.top] = value;
self.top = self.top [1] 1;
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using minus operator which would decrease the top incorrectly.
Using multiplication or division which are not correct here.
✗ Incorrect
We increase the top index by 1 after pushing an element.
3fill in blank
hardFix the error in the pop method to correctly remove and return the top element.
DSA Rust
impl Stack {
fn pop(&mut self) -> Option<i32> {
if self.top == 0 {
None
} else {
self.top = self.top [1] 1;
Some(self.data[self.top])
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Increasing top which would cause out-of-bound errors.
Using multiplication or division which are invalid here.
✗ Incorrect
We decrease the top index by 1 before returning the element.
4fill in blank
hardFill both blanks to check if the stack is empty and to clear it.
DSA Rust
impl Stack {
fn is_empty(&self) -> bool {
self.top [1] 0
}
fn clear(&mut self) {
self.top = [2];
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using not equal in is_empty which gives wrong result.
Setting top to 1 in clear which does not empty stack.
✗ Incorrect
is_empty returns true if top equals 0; clear sets top to 0 to empty stack.
5fill in blank
hardFill all three blanks to implement peek method that returns the top element without removing it.
DSA Rust
impl Stack {
fn peek(&self) -> Option<i32> {
if self.top [1] 0 {
None
} else {
Some(self.data[self.top [2] [3]])
}
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using equality check instead of not equal in condition.
Using plus instead of minus in index causing out-of-bound access.
✗ Incorrect
Peek returns None if empty (top != 0 false), else returns element at top-1 index.
