10.21 First Non-Repeated Character

10.21.1 Problem Metadata

  • Platform: Interview Prep
  • Problem ID: First Unique Character
  • Difficulty: Easy
  • URL: N/A
  • Tags:
  • Techniques: Hash Table, String

10.21.2 Description

Given a string s, return the index of the first non-repeating character. If every character repeats, return -1.

10.21.3 Examples

Input: "GeeksforGeeks"
Output: 5   // 'f'

Input: "GeeksQuiz"
Output: 0   // 'G'

10.21.4 Constraints

  • 1 <= s.length <= 10^5
  • String may contain uppercase and lowercase letters

10.21.5 Solution - Frequency Counting

10.21.5.1 Walkthrough

Count occurrences of every character using an array keyed by ASCII value. A second pass over the string returns the first index with frequency 1.

10.21.5.2 Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1) (size of character set)

10.21.5.3 Implementation Steps

  1. Initialize int[] freq = new int[256].
  2. For each character, increment its count.
  3. Iterate the string again; return the first index where freq[c] == 1.
  4. Return -1 if none.

10.21.5.4 Code - Java

public int firstUniqChar(String s) {
    int[] freq = new int[256];
    for (char c : s.toCharArray()) {
        freq[c]++;
    }
    for (int i = 0; i < s.length(); i++) {
        if (freq[s.charAt(i)] == 1) {
            return i;
        }
    }
    return -1;
}