Share my solution which can extend string stream input

  • 0

    The key idea is to store the index of visited characters, if it is unique, the index is positive, if we have encountered it before, the index is updated as -index. Then we can find min index in the hashmap.

    public int firstUniqChar(String s) {
            Map<Character, Integer> map = new HashMap<>();
            for(int i = 0; i < s.length(); i++) {
                if(map.containsKey(s.charAt(i))) {
                    map.put(s.charAt(i), -i);
                } else {
                    map.put(s.charAt(i), i);
            int minIdx = Integer.MAX_VALUE;
            for(char c : map.keySet()) {
                if(map.get(c) >= 0) {
                    minIdx = Math.min(minIdx, map.get(c));
            return minIdx == Integer.MAX_VALUE? -1 : minIdx;

Log in to reply

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