I have written below code for detecting first duplicate character in a string.
public static int detectDuplicate(String source) {
boolean found = false;
O(1) Algorithm
Your solution is O(n^2) because of the two nested loops.
The fastest algorithm to do this is O(1) (constant time):
public static int detectDuplicate(String source) {
boolean[] foundChars = new boolean[Character.MAX_VALUE+1];
for(int i = 0; i < source.length(); i++) {
if(i >= Character.MAX_VALUE) return Character.MAX_VALUE;
char currentChar = source.charAt(i);
if(foundChars[currentChar]) return i;
foundChars[currentChar] = true;
}
return -1;
}
However, this is only fast in terms of big oh.