Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to add an element to the queue using stack1.
DSA Typescript
enqueue(element: number): void {
this.stack1.[1](element);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pop instead of push to add elements.
Using shift or unshift which are array methods but not stack methods.
✗ Incorrect
To add an element to the queue, we push it onto stack1.
2fill in blank
mediumComplete the code to remove and return the front element from the queue.
DSA Typescript
dequeue(): number | undefined {
if (this.stack2.length === 0) {
while (this.stack1.length > 0) {
this.stack2.[1](this.stack1.pop()!);
}
}
return this.stack2.pop();
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pop on stack2 to transfer elements instead of push.
Using shift or unshift which are not stack methods.
✗ Incorrect
We push elements popped from stack1 onto stack2 to reverse their order for dequeue.
3fill in blank
hardFix the error in the method that checks if the queue is empty.
DSA Typescript
isEmpty(): boolean {
return this.stack1.length [1] 0 && this.stack2.length === 0;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using != instead of == causing wrong empty check.
Using > or < which do not correctly check for zero length.
✗ Incorrect
The queue is empty only if both stacks have zero length, so we check if stack1.length == 0.
4fill in blank
hardFill both blanks to implement the peek method that returns the front element without removing it.
DSA Typescript
peek(): number | undefined {
if (this.stack2.length === 0) {
while (this.stack1.length > 0) {
this.stack2.[1](this.stack1.pop()!);
}
}
return this.stack2[2];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() to return the front element which removes it.
Accessing stack2[0] which is the bottom, not the top of the stack.
✗ Incorrect
We push elements from stack1 to stack2, then return the last element in stack2 without popping it.
5fill in blank
hardFill all three blanks to implement the constructor initializing the two stacks as empty arrays.
DSA Typescript
constructor() {
this.stack1 = [1];
this.stack2 = [2];
this.size = [3];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using null or {} instead of empty arrays for stacks.
Initializing size as null instead of zero.
✗ Incorrect
Stacks are empty arrays and size starts at zero.
