Suppose I have an array like this : [ 1, 2, 3, 4, 5, 6, 1]
I want to get an output like 1 ==> 6 ( For element 1(0th index the match is found at index 6)
This means for 0th element the next match is found at 6th index.
If the input is [4,6,4,6]
the output is 4 ==> 2 and 6 ==> 3
Since first match for 4 is found at index 2( which is four) and first match for six(2nd element) is found at 3rd index
If the time complexity is O(n2) the solution is pretty straight forward. I have tried to find the next greatest element with this code in O(n) using stack. But I couldn't find a way to do the same for next equal element.
import java.util.Scanner;
import java.util.Stack;
public class NextGreatestElement {
public static void main(String[] args) {
int[] inp = {1,4,6,2,39};
Stack<Integer> stack = new Stack<>();
stack.push(inp[0]);
for (int i = 1; i < inp.length; i++) {
int element = inp[i];
if (element > stack.peek()) {
System.out.println(stack.peek() + " ==> " + element);
stack.pop();
while (!stack.isEmpty()) {
System.out.println(stack.pop() + " ==> " + element);
}
stack.push(element);
} else if (element < stack.peek()) {
stack.push(element);
}
}
while (!stack.isEmpty()) System.out.println(stack.pop() + " ==> " + (-1));
}
}
Even Algorithm is enough. I don't need the code.