functionnextGreaterElement(arr) {constanswer= [];for (let i =0; i <arr.length; i++) {constcurr= i;let idx = (i +1) %arr.length;while (idx !== i) {if (arr[curr] < arr[idx]) { answer[curr] = arr[idx];break; } idx++; idx %=arr.length; }if (idx === i) { answer[curr] =-1; } }return answer;}// Do not edit the line below.exports.nextGreaterElement = nextGreaterElement;
optimized with using stack ⇒ pick from latest element
n, n
functionnextGreaterElement(arr) {constanswer=newArray(arr.length).fill(-1);constlen=arr.length*2;conststack= [];for (let i = len -1; i >=0; --i) {constidx= i %arr.length;constcurrentValue= arr[idx];while (stack.length>0) {if (stack[stack.length-1 ] <= currentValue) {consttop=stack.pop(); } else { answer[idx] = stack[stack.length-1];break; } }stack.push(currentValue); }return answer;}// Do not edit the line below.exports.nextGreaterElement = nextGreaterElement;