Site Search:

First Unique Character in a String

Problem

Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.

Examples:

s = "leetcode"

return 0.

s = "loveleetcode"

return 2.

Note: You may assume the string contains only lowercase English letters.

Solution

We can iterate the string characters, create the frequency map, then we iterate it second time, look up the frequency of each character. The first character with frequency 1 is the answer.

import java.util.*;

class Solution {
  
  public static void main(String[] args) {
    String in = "eebb";
    System.out.println(solve(in));
  }
  private static int solve(String str) {
    //leetcode
    Map<Character, Integer> map = new HashMap<>();
    for(char c : str.toCharArray()) {
      map.put(c, map.getOrDefault(c, 0) + 1);
    }
    //l 1, e 3...
    for(int i = 0; i < str.length(); i++) {
      if(map.get(str.charAt(i)) == 1)
        return i;
    }
    return -1;
  }
}

The time complexity is O(N) and space complexity is O(N).