I have written below code for detecting first duplicate character in a string.
public static int detectDuplicate(String source) {
boolean found = false;
Okay, I found below logic to reduce O(N^2)
to O(N)
.
public static int detectDuplicate(String source) {
int index = -1;
boolean found = false;
final long start = System.currentTimeMillis();
for(int i = 1; i <= source.length() && !found; i++) {
if(source.charAt(i) == source.charAt(i-1)) {
index = (i - 1);
found = true;
}
}
System.out.println("Time taken --> " + (System.currentTimeMillis() - start) + " ms. for string of length --> " + source.length());
return index;
}
This also shows performance improvement over my previous algorithm which has 2 nested loops. This takes 130ms.
to detect first duplicate character from 63million
characters where the duplicate character is present at the end.
I am not confident if this is the best solution. If anyone finds a better one, please please share it.
Thanks,
NN