function firstLargeNum(num) { let i = 0; let ans = [], stack = []; for (i = num.length - 1; i >= 0; i--) { while (stack.length > 0) { let top = stack[stack.length - 1]; if (top > num[i]) { ans.unshift(top); break; } else { stack.pop(); } } if (stack.length === 0) { ans.unshift(-1); } stack.push(num[i]); } return ans; } console.log(firstLargeNum([3, 2, 1, 2, 6, 2, 3]));