Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Programming Challenge: How to find the first non-repeating character in a string

2. How to find the first non-repeating character in a string?

In text processing tasks, it's common to identify the first character in a string that does not repeat. This problem helps assess a developer’s ability to use hash maps and efficient string traversal techniques.

Problem:

  • Given a string s, return the index of the first non-repeating character.
  • If there is no such character, return -1.
  • The string contains only lowercase English letters.

Example:

  • Input: "leetcode" → Output: 0
  • Input: "loveleetcode" → Output: 2
  • Input: "aabb" → Output: -1

Java Implementation:


import java.util.*;

public class FirstUniqueChar {
    public int firstUniqChar(String s) {
        Map<Character, Integer> countMap = new HashMap<>();
        
        // First pass: count frequency
        for (char c : s.toCharArray()) {
            countMap.put(c, countMap.getOrDefault(c, 0) + 1);
        }

        // Second pass: find the first character with count 1
        for (int i = 0; i < s.length(); i++) {
            if (countMap.get(s.charAt(i)) == 1) {
                return i;
            }
        }

        return -1;
    }

    public static void main(String[] args) {
        FirstUniqueChar finder = new FirstUniqueChar();
        System.out.println(finder.firstUniqChar("loveleetcode")); // Output: 2
    }
}
                

Time Complexity: O(N), where N is the length of the string.

Space Complexity: O(1), since the map size is limited to 26 lowercase letters.

Use Cases:

  • Chat moderation systems (detect unique abusive terms)
  • Data preprocessing before tokenization
  • String validation in compilers or interpreters