First Non-Repeating Character in a String

Problem

Find the first non-repeating character in a string and return its index, or -1 if none exists.

Input:  s = "leetcode"
Output: 0   ('l' never repeats)

Python Solution

def first_uniq_char(s):
    counts = {}
    for ch in s:
        counts[ch] = counts.get(ch, 0) + 1
    for i, ch in enumerate(s):
        if counts[ch] == 1:
            return i
    return -1

C++ Solution

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

Java Solution

class Solution {
    public int firstUniqChar(String s) {
        int[] counts = new int[26];
        for (char ch : s.toCharArray()) counts[ch - 'a']++;
        for (int i = 0; i < s.length(); i++) {
            if (counts[s.charAt(i) - 'a'] == 1) return i;
        }
        return -1;
    }
}

Complexity

Time: O(n) — one pass to count, one pass to find the first count of 1. Space: O(1) for lowercase letters (fixed 26-slot array).

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.