Advertisement
satishfrontenddev4

Untitled

Jan 5th, 2024
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Given an array, print the next smaller element for every element. The next smaller element for an element x is the first smaller element on the right side of x in the array. Elements for which no next smaller element exists, consider it as -1.
  3.  
  4. Input format
  5. First line contains an integer N - The size of the array.
  6.  
  7. Second line contains N space separated integers - The given array.
  8.  
  9. Output format
  10. Print in a single line, the next smaller element for each array element separated by space.
  11.  
  12. Sample Input 1
  13. 5
  14.  
  15. 8 2 5 10 4
  16.  
  17. Sample Output 1
  18. 2 -1 4 4 -1
  19.  
  20. Explanation
  21. In the given array, next smaller element to 8 is 2 and for 5 & 10 it is 4. For 2 and 4 the next smaller element does not exist so the final ans is [2, -1, 4, 4, -1].
  22.  
  23. Constraints
  24. 1 <= N <= 10^5
  25.  
  26. 0 <= A[i] <= 10^9
  27. */
  28.  
  29. /**
  30.  * @param {number} n
  31.  * @param {number[]}arr
  32.  * @return {number[]}
  33.  */
  34. function nextSmallerElement(n,arr) {
  35.     const ans = new Array(n).fill(-1);
  36.     let stack=[];
  37.     for(let i=n-1;i>=0;i--){
  38.         let curr=arr[i];
  39.         let nextSmaller=-1;
  40.         while(stack.length!=0){
  41.             let top=stack[stack.length-1];
  42.             if(top>=curr){
  43.                 stack.pop()
  44.             }
  45.             else{
  46.                 nextSmaller=top;
  47.                 break;
  48.             }
  49.         }
  50.         ans[i]=nextSmaller;
  51.         stack.push(curr);  
  52.     }
  53.    
  54.     return ans;
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement