Skip to main content

First Unique Character in a String - LeetCode Daily Challenge

Prerna Sharma

Problem Statement

Given a string sfind the first non-repeating character in it, and return its index. If it does not exist, return -1.

Example 1

Input: s = "innoskrit"
Output: 3

Example 2

Input: s = "loveinnoskrit"
Output: 0

Try here before watching the video.

Video Solution

Java Code

class Solution {
    public int firstUniqChar(String s) {
        
        Map<Character, Integer> map = new HashMap<>();
        for(char ch : s.toCharArray()) {
            map.put(ch, map.getOrDefault(ch, 0) + 1);
        }
        for(int i = 0; i < s.length(); i++) {
            if(map.get(s.charAt(i)) == 1) {
                return i;
            }
        }
        return -1;
    }
}

C++ Code

class Solution {
public:
    int firstUniqChar(string s) {
        unordered_map<char, int> map;
        for (char ch : s) {
            map[ch]++;
        }
        for (int i = 0; i < s.length(); i++) {
            if (map[s[i]] == 1) {
                return i;
            }
        }
        return -1;
    }
};

Python Code

class Solution:
    def firstUniqChar(self, s: str) -> int:
        char_count = {}
        for ch in s:
            char_count[ch] = char_count.get(ch, 0) + 1
        for i, ch in enumerate(s):
            if char_count[ch] == 1:
                return i
        return -1

Javascript Code

var firstUniqChar = function(s) {
    let map = new Map();
    for (let ch of s) {
        map.set(ch, (map.get(ch) || 0) + 1);
    }
    for (let i = 0; i < s.length; i++) {
        if (map.get(s[i]) === 1) {
            return i;
        }
    }
    return -1;
};

Go Code

func firstUniqChar(s string) int {
    m := make(map[rune]int)
    for _, ch := range s {
        m[ch]++
    }
    for i, ch := range s {
        if m[ch] == 1 {
            return i
        }
    }
    return -1
}

Complexity Analysis

  • Time complexity: O(N), since we go through the string of length N two times.
  • Space complexity: O(1), because the English alphabet contains 26 letters.