less than 1 minute read

1 min read 275 words

Problem Statement

leetcode problem link

Solution [accepted]

public class Solution {
    public int FirstUniqChar(string s) {
        Dictionary<char, int> freq = new Dictionary<char, int>();
        foreach (var c in s) {
            freq[c] = freq.GetValueOrDefault(c, 0) + 1;
        }
        for (var i = 0; i < s.Length; i++) {
            var c = s[i];
            if (freq[c] == 1) {
                return i;
            }
        }
        return -1;
    }
}

Editorial

Approach 1: Linear time solution

class Solution:
    def firstUniqChar(self, s: str) -> int:
        """
        :type s: str
        :rtype: int
        """
        # build hash map: character and how often it appears
        count = collections.Counter(s)

        # find the index
        for idx, ch in enumerate(s):
            if count[ch] == 1:
                return idx
        return -1

Leave a comment