Adding a Java 100/100 O(N) time with O(1) space:
https://codility.com/demo/results/demoPNG8BT-KEH/
class Solution {
public int solution(int[] A) {
int indexOfCandidate = -1;
int stackCounter = 0, candidate=-1, value=-1, i =0;
for(int element: A ) {
if (stackCounter == 0) {
value = element;
++stackCounter;
indexOfCandidate = i;
} else {
if (value == element) {
++stackCounter;
} else {
--stackCounter;
}
}
++i;
}
if (stackCounter > 0 ) {
candidate = value;
} else {
return -1;
}
int countRepetitions = 0;
for (int element: A) {
if( element == candidate) {
++countRepetitions;
}
if(countRepetitions > (A.length / 2)) {
return indexOfCandidate;
}
}
return -1;
}
}
If you want to see the Java source code it's here, I added some test cases as comments as the beginning of the file.