One Pager Cheat Sheet
- Write a method
nextLargerNumber(nums: array)
to print the next immediate larger number for every element in a circular array, managing constraints of time & space complexity ofO(n)
. - We
iterate
through the normal array until we find the next immediate larger element. - Using any of the established solutions such as
ring buffers
orcircular queues
, we can effectively utilize acircular array
to check each element against numbers both before and after. - We can avoid double iteration with a big time complexity of
O(n^2)
by finding a faster way to compare each element with every other one. - We can improve the speed of our comparison by using a
stack
to do one pass instead of nested loop. - Using a
for-loop
to iterativelypop
and compare elements, the algorithm determines thenext greater element
for each element in the array in acircular
fashion. - The final step is to
push
thenext
element onto thestack
and thenpop
all remaining elements, setting-1
as thenext greater element
for them.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx
29
var assert = require('assert');
​
function nextLargerNumber(nums) {
const result = [];
const stack = [];
for (let j = 0; j < nums.length; j++) {
result.push(-1);
}
for (let i = 0; i < nums.length * 2; i++) {
let num = nums[i % nums.length];
while (stack.length && nums[stack[stack.length - 1]] < num) {
result[stack.pop()] = num;
}
if (i < nums.length) {
stack.push(i);
}
}
return result;
}
​
try {
assert.deepEqual(nextLargerNumber([3, 1, 3, 4]), [4, 3, 4, -1]);
​
console.log(
'PASSED: assert.deepEqual(nextLargerNumber([3, 1, 3, 4]), [4, 3, 4, -1])'
);
} catch (err) {
console.log(err);
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Got more time? Let's keep going.
If you had any problems with this tutorial, check out the main forum thread here.