As mentioned by others, your algorithm is O (n ^ 2). Here is the O (N) algorithm, because HashSet # adds runs in constant time (the hash function correctly distributes elements among buckets). Please note that I initially made the hash size the maximum size to avoid resizing / renaming:
public static int findDuplicate(String s) { char[] chars = s.toCharArray(); Set<Character> uniqueChars = new HashSet<Character> (chars.length, 1); for (int i = 0; i < chars.length; i++) { if (!uniqueChars.add(chars[i])) return i; } return -1; }
Note: this returns the index of the first duplicate (i.e. the index of the first character, which is a duplicate of the previous character). To return the index of the first occurrence of this symbol, you need to save the indices in Map<Character, Integer> ( Map#put also O (1) in this case):
public static int findDuplicate(String s) { char[] chars = s.toCharArray(); Map<Character, Integer> uniqueChars = new HashMap<Character, Integer> (chars.length, 1); for (int i = 0; i < chars.length; i++) { Integer previousIndex = uniqueChars.put(chars[i], i); if (previousIndex != null) { return previousIndex; } } return -1; }
source share