Next Greater Element (Right)
JavaScript
Medium
6 views
Problem Description
For each element, find the next greater element on its right side. If none, print -1 at that position.
Input Format
One line: n then n integers.
Output Format
One line: n integers.
Official Solution
const fs=require('fs');const p=fs.readFileSync(0,'utf8').trim().split(/\\s+/);if(!p[0])process.exit(0);let i=0;const n=Number(p[i++]);let arr=new Array(n);for(let j=0;j<n;j++)arr[j]=Number(p[i++]);let ans=new Array(n).fill(-1);let st=[];for(let j=0;j<n;j++){while(st.length && arr[st[st.length-1]]<arr[j]){ans[st.pop()]=arr[j];}st.push(j);}process.stdout.write(ans.join(' '));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!