Java One Pass Solution with LinkedHashMap

  • 9

    LinkedHashMap will not be the fastest answer for this question because the input characters are just from 'a' to 'z', but in other situations it might be faster than two pass solutions. I post this just for inspiration.

    public int firstUniqChar(String s) {
            Map<Character, Integer> map = new LinkedHashMap<>();
            Set<Character> set = new HashSet<>();
            for (int i = 0; i < s.length(); i++) {
                if (set.contains(s.charAt(i))) {
                    if (map.get(s.charAt(i)) != null) {
                } else {
                    map.put(s.charAt(i), i);
            return map.size() == 0 ? -1 : map.entrySet().iterator().next().getValue();

  • 2

    I think you can replace if (map.get(s.charAt(i)) != null) {map.remove(s.charAt(i));}
    with map.remove(s.charAt(i));

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.