Learn
Practice
Interview
Resources
Newsletter
F
Toggle theme
0
F
0
Toggle menu
Animations
← Back to All Animations
Next Greater Element II
Bookmark
Brute Force
Monotonic Stack
Input
Input 1
Input 2
Input 3
Custom
nums
=
[1, 2, 1]
↻ circular array — scans wrap past the end
nums
1
0
2
1
1
2
result
↻ circular array — scans wrap past the end
nums
1
0
2
1
1
2
result
↻ circular array — scans wrap past the end
nums
1
0
2
1
1
2
result
↻ circular array — scans wrap past the end
nums
1
0
2
1
1
2
i
result
index
1
: scan forward, wrapping around, for a bigger value
↻ circular array — scans wrap past the end
nums
1
0
2
1
1
2
i
result
2
index
2
: scan forward, wrapping around, for a bigger value
↻ circular array — scans wrap past the end
nums
1
0
2
1
1
2
j
i
result
2
1
<= 2 → keep scanning
↻ circular array — scans wrap past the end
nums
1
0
2
1
1
2
j
i
result
2
1
<= 2 → keep scanning
(wrapped)
↻ circular array — scans wrap past the end
nums
1
0
2
1
1
2
j
i
result
2
-1
nothing bigger in the whole circle →
-1
↻ circular array — scans wrap past the end
nums
1
0
2
1
1
2
j
i
result
2
-1
1
<= 1 → keep scanning
(wrapped)
↻ circular array — scans wrap past the end
nums
next greater (wrapped)
1
0
2
1
1
2
j
i
result
2
-1
2
2
> 1 → result[2] = 2
nums
1
0
2
1
1
2
result
2
-1
2
return
[2, -1, 2]
algo
master
.
io
Step:
Brute force: for each element, scan the array circularly for the next greater.
0 / 11
Input
Input 1
Input 2
Input 3
Custom
nums
=
[1, 2, 1]
0 / 11
algo
master
.
io
Step:
Brute force: for each element, scan the array circularly for the next greater.