Next Greater Element Using Stack in DSA Typescript - Time & Space Complexity
We want to understand how the time needed to find the next greater element changes as the list grows.
How does the number of steps grow when we check each number against others using a stack?
Analyze the time complexity of the following code snippet.
function nextGreaterElement(nums: number[]): number[] {
const stack: number[] = [];
const result: number[] = new Array(nums.length).fill(-1);
for (let i = 0; i < nums.length; i++) {
while (stack.length > 0 && nums[i] > nums[stack[stack.length - 1]]) {
const index = stack.pop()!;
result[index] = nums[i];
}
stack.push(i);
}
return result;
}
This code finds the next greater number for each element in the array using a stack to keep track of indices.
- Primary operation: The for-loop runs through each element once.
- How many times: Each element is pushed and popped from the stack at most once.
As the input size grows, each element is handled a limited number of times, so the total steps grow roughly in direct proportion to the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 operations (push and pop per element) |
| 100 | About 200 operations |
| 1000 | About 2000 operations |
Pattern observation: The operations grow roughly linearly with input size.
Time Complexity: O(n)
This means the time to find next greater elements grows in a straight line as the list gets longer.
[X] Wrong: "Because there is a nested while inside the for-loop, the time must be O(n²)."
[OK] Correct: Each element is pushed and popped only once, so the inner loop does not run for every element repeatedly.
Understanding this pattern helps you solve many problems where you need to find the next bigger or smaller item efficiently.
"What if we changed the input to a circular array where the search wraps around? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem goal
The Next Greater Element problem aims to find, for each element, the first element to its right that is larger than it.Step 2: Identify the role of the stack
A stack helps efficiently track elements for which we haven't found a greater element yet, allowing us to find the next greater element in one pass.Final Answer:
The first greater element to the right of each element -> Option BQuick Check:
Next Greater Element = first bigger right element [OK]
- Confusing next greater with next smaller element
- Searching to the left instead of right
- Thinking it sums elements instead of finding one
Solution
Step 1: Identify correct stack data structure
For Next Greater Element, a stack is an array used with push/pop. So, an empty array of numbers is correct.Step 2: Check TypeScript syntax
const stack: number[] = []; correctly declares an empty number array stack.Final Answer:
const stack: number[] = []; -> Option CQuick Check:
Stack = number array [] [OK]
- Using object {} instead of array for stack
- Initializing stack as null
- Using Map which is not a stack
[4, 5, 2, 25]?Solution
Step 1: Process each element to find next greater
4's next greater is 5, 5's next greater is 25, 2's next greater is 25, 25 has none so -1.Step 2: Form the output array
Output array is [5, 25, 25, -1].Final Answer:
[5, 25, 25, -1] -> Option AQuick Check:
Next Greater Element for [4,5,2,25] = [5,25,25,-1] [OK]
- Assigning -1 too early
- Mixing up order of elements
- Confusing next greater with next smaller
function nextGreater(arr: number[]): number[] {
const stack: number[] = [];
const result: number[] = new Array(arr.length).fill(-1);
for (let i = 0; i < arr.length; i++) {
while (stack.length && arr[stack[stack.length]] < arr[i]) {
const index = stack.pop();
result[index] = arr[i];
}
stack.push(i);
}
return result;
}Solution
Step 1: Check stack top element access
stack[stack.length] is undefined because array indices go from 0 to length-1. Correct is stack[stack.length - 1].Step 2: Confirm other parts are correct
Result array initialization and loop direction are correct. Stack stores indices as expected.Final Answer:
Incorrect stack top access: should be stack[stack.length - 1] -> Option DQuick Check:
Stack top index = stack[stack.length - 1] [OK]
- Using stack[stack.length] which is undefined
- Initializing result with wrong default
- Reversing loop unnecessarily
[13, 7, 6, 12], what is the Next Greater Element array using a stack approach?Solution
Step 1: Find next greater for each element
13 has no greater element to right, so -1. 7's next greater is 12. 6's next greater is 12. 12 has none, so -1.Step 2: Write the output array
The result is [-1, 12, 12, -1].Final Answer:
[-1, 12, 12, -1] -> Option AQuick Check:
Next Greater Element for [13,7,6,12] = [-1,12,12,-1] [OK]
- Assigning wrong next greater for 13
- Mixing up indices and values
- Confusing next greater with previous greater
Ready to prove it?
Pass the test and this pattern moves unknown
