Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1398 from loczek/496-Next-Greater-Elem…
Browse files Browse the repository at this point in the history
…ent-I

Create: 496-Next-Greater-Element-I.ts
  • Loading branch information
Ahmad-A0 authored Nov 2, 2022
2 parents 2a78cc9 + 5104d3a commit 869a3ce
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions typescript/496-Next-Greater-Element-I.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
function nextGreaterElement(nums1: number[], nums2: number[]): number[] {
const map = {};

for (let i = 0; i < nums1.length; i++) {
map[nums1[i]] = i;
}

let res = new Array(nums1.length).fill(-1);
const stack: number[] = [];

for (let i = 0; i < nums2.length; i++) {
let cur = nums2[i];
while (stack.length && cur > stack.at(-1)) {
let val = stack.pop()!;
let idx = map[val];
res[idx] = cur;
}
if (map.hasOwnProperty(cur)) {
stack.push(cur);
}
}

return res;
}

0 comments on commit 869a3ce

Please sign in to comment.