Saturday, February 19, 2022

Next Greater Element To The Right

I/P: {1, 3, 4, 7, 2, 6, 8} 

O/P: {3, 4, 7, 8, 6, 8, -1} 







package pep.Day25;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Stack;

public class Next_Greater_Element_To_The_RIght {
public static void main(String[] args) {
int[] arr = new int[]{1, 3, 4, 7, 2, 6, 8};

int[] ans = solve(arr);
display(ans);
}

private static void display(int[] ans) {
for (int i : ans)
System.out.print(i + "\t");

System.out.println();
}

private static int[] solve(int[] arr) {
int n = arr.length;
Stack<Integer> stack = new Stack<>();
int[] ans = new int[n];

for (int i = n - 1; i >= 0; i--) {
while (!stack.isEmpty() && stack.peek() <= arr[i])
stack.pop();
ans[i] = stack.isEmpty() ? -1 : stack.peek();
stack.push(arr[i]);
}
return ans;
}

}


Time Complexity: O(n)

Space Complexity: O(n)



No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...