Below code works fine but it is in the complexity of O(n^2). Is it possible to do it O(n) or O(log n) time.
public class TwoRepeatingElements {
public static void main(String[] args) {
Integer array[] = {4, 2, 4, 5, 2, 3, 1, 2};
findTwoRepeatingElements(array);
}
private static void findTwoRepeatingElements(Integer[] array) {
int i, j;
for(i = 0; i < array.length-1; i++) {
for(j = i+1; j < array.length-1; j++) {
if(array[i] == array[j]) {
System.out.println(array[i]);
}
}
}
}
}
This solution runs in O(n) time, notice that if you only need to find one repeated element, you can exit the loop as soon as you find it:
EDIT
If you need to print the repeated elements only once, this solution uses a little more memory since two sets are needed, but it’s still O(n). Take a look at this: