Skip to content

Instantly share code, notes, and snippets.

@tiagopereira17
Created July 9, 2016 13:59
Show Gist options
  • Save tiagopereira17/377a0993bdaef6ce6de6268322a246cb to your computer and use it in GitHub Desktop.
Save tiagopereira17/377a0993bdaef6ce6de6268322a246cb to your computer and use it in GitHub Desktop.
Find the index S such that the leaders of the sequences A[0], A[1], ..., A[S] and A[S + 1], A[S + 2], ..., A[N - 1] are the same.
import java.util.Stack;
public class EquiLeader {
public int solution(int[] A) {
if(A == null || A.length == 0) {
return 0;
}
Stack<Integer> stack = new Stack<>();
for(int i = 0; i < A.length; i++) {
if(stack.isEmpty()) {
stack.push(A[i]);
continue;
}
if(stack.peek() != A[i]) {
stack.pop();
} else {
stack.push(A[i]);
}
}
if(stack.isEmpty()) {
return 0;
}
int candidate = stack.pop();
int leaderCounter = 0;
for(int i = 0; i < A.length; i++) {
if(A[i] == candidate) {
leaderCounter++;
}
}
if(leaderCounter <= A.length / 2) {
return 0;
}
int equiLeaders = 0;
double currentLeaderCount = 0.0;
for(int i = 0; i < A.length; i++) {
if(A[i] == candidate) {
currentLeaderCount++;
}
if(currentLeaderCount > (i + 1.0) / 2.0 && leaderCounter - currentLeaderCount > (A.length - 1.0 - i) / 2.0) {
equiLeaders++;
}
}
return equiLeaders;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment