Lesson 1 · Unit 04
Next greater element
A stack of waiting indexes answers every position in one pass
What you practise
- A decreasing stack of indexes
- O(n) because each index is pushed and popped once
Try a question from this lesson
Pick one
Daily temperatures: [70, 68, 71, 69, 75]. For each day you want the number of days until a warmer one. What is the answer for day 0, the 70?
Correct answer
2
Why
Day 1 is colder (68), day 2 is warmer (71), so the wait is 2 days. Checking each day by scanning to its right is O(n²) in the worst case. This lesson gets every answer in one pass.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
A stack of waiting indexes
To find the next larger value for every item, keep a stack of the indexes that are still waiting for one.
A new value x is the answer for every waiting index whose value is smaller: pop each one and record x. Then the new index waits too. Anything left at the end keeps -1.
a = [2, 7, 3, 5, 4, 6]
out = [-1] * len(a)
st = []
for i, x in enumerate(a):
while st and a[st[-1]] < x:
out[st.pop()] = x
st.append(i)
print(*out)const a = [2, 7, 3, 5, 4, 6];
const out = a.map(() => -1);
const st = [];
for (const [i, x] of a.entries()) {
while (st.length && a[st.at(-1)] < x) {
out[st.pop()] = x;
}
st.push(i);
}
console.log(...out);const a = [2, 7, 3, 5, 4, 6];
const out = a.map(() => -1);
const st: number[] = [];
for (const [i, x] of a.entries()) {
while (st.length && a[st.at(-1)!] < x) {
out[st.pop()!] = x;
}
st.push(i);
}
console.log(...out);Python notest[-1] is the top of the stack. An empty list counts as false, so while st stops when nothing is waiting.
JavaScript notea.entries() yields [index, item] pairs. st.at(-1) is the last item of an array, the top of the stack.
TypeScript notest.at(-1) and st.pop() have type number | undefined, because the stack might be empty. The ! says you know it is not: st.length was just checked.
10 more exercises in the app
- 2× type the answer
- 4× multiple choice
- 2× fill the blanks
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.