Skip to content

Instantly share code, notes, and snippets.

@harbirchahal
Created May 21, 2022 06:50
Show Gist options
  • Save harbirchahal/73daa96615bc0ee6d5b46b6972622f79 to your computer and use it in GitHub Desktop.
Save harbirchahal/73daa96615bc0ee6d5b46b6972622f79 to your computer and use it in GitHub Desktop.
Next greater or smaller element in array
/*
Next greater element left or right
Next smaller element left or right
*/
// [1, 3, 2, 4] => [-1, 1, 1, 2]
// [1, 3, 0, 0, 1, 2, 4] => [-1, 1, -1, -1, 0, 1, 2]
function nextSmallerLeft(nums) {
const ans = [];
const stack = [];
for (let i = 0; i < nums.length; i++) {
while (stack.length && stack[0] >= nums[i]) {
stack.shift();
}
ans[i] = stack.length ? stack[0] : -1;
stack.unshift(nums[i]);
}
return ans;
}
// [1, 3, 2, 4] => [-1, 2, -1, -1]
// [1, 3, 0, 0, 1, 2, 4] => [0, 0, -1, -1, -1, -1, -1]
function nextSmallerRight(nums) {
const ans = [];
const stack = [];
for (let i = nums.length - 1; i >= 0; i--) {
while (stack.length && stack[0] >= nums[i]) {
stack.shift();
}
ans[i] = stack.length ? stack[0] : -1;
stack.unshift(nums[i]);
}
return ans;
}
// [1, 3, 2, 4] => [-1, -1, 3, -1]
// [1, 3, 0, 0, 1, 2, 4] => [-1, -1, 3, 3, 3, 3, -1]
function nextGreaterLeft(nums) {
const ans = [];
const stack = [];
for (let i = 0; i < nums.length; i++) {
while (stack.length && stack[0] <= nums[i]) {
stack.shift();
}
ans[i] = stack.length ? stack[0] : -1;
stack.unshift(nums[i]);
}
return ans;
}
// [1, 3, 2, 4] => [3, 4, 4, -1]
// [1, 3, 0, 0, 1, 2, 4] => [3, 4, 1, 1, 2, 4, -1]
function nextGreaterRight(nums) {
const ans = [];
const stack = [];
for (let i = nums.length - 1; i >= 0; i--) {
while (stack.length && stack[0] <= nums[i]) {
stack.shift();
}
ans[i] = stack.length ? stack[0] : -1;
stack.unshift(nums[i]);
}
return ans;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment