Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to add an element to the stack using a queue.
DSA Typescript
push(x: number): void {
this.queue.push([1]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using shift() or pop() instead of adding the new element.
Passing undefined instead of the element.
✗ Incorrect
To push an element onto the stack, we add it to the queue using push(x).
2fill in blank
mediumComplete the code to remove the top element from the stack using the queue.
DSA Typescript
pop(): number | undefined {
for (let i = 0; i < this.queue.length - 1; i++) {
this.queue.push(this.queue.[1]());
}
return this.queue.shift();
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() which removes the last element instead of the first.
Using push() or unshift() which add elements instead of removing.
✗ Incorrect
We use shift() to remove the front element and push it back to rotate the queue until the last element remains.
3fill in blank
hardFix the error in the peek method to return the top element without removing it.
DSA Typescript
peek(): number | undefined {
for (let i = 0; i < this.queue.length - 1; i++) {
this.queue.push(this.queue.shift());
}
const top = this.queue.[1]();
this.queue.push(this.queue.shift());
return top;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() which removes the last element.
Using push() or unshift() which add elements.
✗ Incorrect
We use shift() to get the front element without removing it permanently by pushing it back immediately.
4fill in blank
hardFill both blanks to check if the stack is empty.
DSA Typescript
isEmpty(): boolean {
return this.queue.[1] === [2];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using size which is not a property of arrays in TypeScript.
Comparing length to null instead of 0.
✗ Incorrect
We check if the queue's length is 0 to determine if the stack is empty.
5fill in blank
hardFill all three blanks to implement the push method that rotates the queue to simulate stack behavior.
DSA Typescript
push(x: number): void {
this.queue.push([1]);
for (let i = 0; i < this.queue.[2] - 1; i++) {
this.queue.push(this.queue.[3]());
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() instead of shift() for rotation.
Using wrong property instead of length.
Not rotating the queue after push.
✗ Incorrect
We add the new element x, then rotate the queue by removing from front (shift) and adding to back to keep the last pushed element at front.
