Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the stack as an empty array.
DSA Javascript
const stack = [1];Attempts:
3 left
💡 Hint
Common Mistakes
Using {} which creates an object, not an array.
Using null or 0 which are not arrays.
✗ Incorrect
In JavaScript, an empty array is created using []. This is used to implement the stack.
2fill in blank
mediumComplete the code to push the current element onto the stack.
DSA Javascript
stack.[1](nums[i]);Attempts:
3 left
💡 Hint
Common Mistakes
Using pop which removes elements instead of adding.
Using shift or unshift which operate on the start of the array.
✗ Incorrect
The push() method adds one or more elements to the end of an array, which is how we add elements to the stack.
3fill in blank
hardFix the error in the while loop condition to check if the stack is not empty.
DSA Javascript
while (stack.[1] > 0 && nums[stack[stack.length - 1]] < nums[i]) {
Attempts:
3 left
💡 Hint
Common Mistakes
Using size or count which are not valid for arrays in JavaScript.
Using length() with parentheses which causes an error.
✗ Incorrect
In JavaScript, arrays have a length property (without parentheses) to get the number of elements.
4fill in blank
hardFill both blanks to pop the top index from the stack and assign the next greater element.
DSA Javascript
const topIndex = stack.[1](); result[topIndex] = nums[[2]];
Attempts:
3 left
💡 Hint
Common Mistakes
Using push instead of pop to remove elements.
Using stack.length - 1 instead of i for the next greater element.
✗ Incorrect
pop() removes the top element from the stack. The next greater element is nums[i], where i is the current index.
5fill in blank
hardFill all three blanks to complete the function that returns the next greater elements array.
DSA Javascript
function nextGreaterElement(nums) {
const result = new Array(nums.length).fill(-1);
const stack = [];
for (let [1] = 0; [1] < nums.length; [1]++) {
while (stack.length > 0 && nums[stack[stack.length - 1]] < nums[[2]]) {
const topIndex = stack.pop();
result[topIndex] = nums[[2]];
}
stack.[3]([1]);
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using j instead of i for the loop variable.
Using pop instead of push to add elements to the stack.
✗ Incorrect
The loop variable is i. We compare nums[stack top] with nums[i]. We push i onto the stack.
