
Sponsored
Sponsored
This approach employs a hash map to store the frequency of each character in the string. Then, by iterating through the string again, we can find the first character with a frequency of 1 and return its index. If no such character is found, we return -1.
Time Complexity: O(n), where n is the length of the string, as we traverse through the string twice.
Space Complexity: O(1), because the array size is constant (26 letters of the English alphabet).
1import java.util.HashMap;
2
3public class FirstUniqueCharacter {
4 public static int firstUniqChar(String s) {
5 HashMap<Character, Integer> freq = new HashMap<>();
6 for (char c : s.toCharArray()) {
7 freq.put(c, freq.getOrDefault(c, 0) + 1);
8 }
9 for (int i = 0; i < s.length(); i++) {
10 if (freq.get(s.charAt(i)) == 1) {
11 return i;
12 }
13 }
14 return -1;
15 }
16
17 public static void main(String[] args) {
18 String s = "leetcode";
19 System.out.println(firstUniqChar(s));
20 }
21}This Java solution iterates through the string and populates a HashMap with the frequency of each character. We then iterate through the string again and return the index of the first character with a frequency of 1.
This approach involves iterating through the input string two times without using any auxiliary space like a hash map or dictionary. In the first iteration, we use an array to count the occurrences of each character. In the second iteration, we check for the first character that appears only once by referring to the count array. We conclude by returning its index or -1 if no such character is found.
Time Complexity: O(n)
Space Complexity: O(1)
This Python variant sets up a list of size 26 to manage character frequency tracking. A second iteration helps find the initial non-redundant character's index.