import java.util.*; public class Main { public static int firstNonRepeatingChar(String s) { Map<Character, Integer> countMap = new HashMap<>(); for (char c : s.toCharArray()) { countMap.put(c, countMap.getOrDefault(c, 0) + 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) { System.out.println(firstNonRepeatingChar("swiss")); } }
The string "swiss" has characters: s, w, i, s, s.
Counting occurrences: s=3, w=1, i=1.
The code checks characters in order and returns the index of the first character with count 1, which is 'w' at index 1.
import java.util.*; public class Main { public static int firstNonRepeatingChar(String s) { Map<Character, Integer> countMap = new HashMap<>(); for (char c : s.toCharArray()) { countMap.put(c, countMap.getOrDefault(c, 0) + 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) { System.out.println(firstNonRepeatingChar("aabbcc")); } }
All characters in "aabbcc" appear twice.
So, there is no non-repeating character.
The function returns -1 when none found.
import java.util.*; public class Main { public static int firstNonRepeatingChar(String s) { Map<Character, Integer> countMap = new HashMap<>(); for (int i = 0; i <= s.length(); i++) { char c = s.charAt(i); countMap.put(c, countMap.getOrDefault(c, 0) + 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) { System.out.println(firstNonRepeatingChar("hello")); } }
The first for loop uses i <= s.length(), which tries to access s.charAt(s.length()), an invalid index.
This causes StringIndexOutOfBoundsException at runtime.
A hash map stores each character's count so we can check if a character is unique in constant time.
This allows scanning the string twice efficiently: once to count, once to find the first unique.
import java.util.*; public class Main { public static int firstNonRepeatingChar(String s) { Map<Character, Integer> countMap = new HashMap<>(); for (char c : s.toCharArray()) { countMap.put(c, countMap.getOrDefault(c, 0) + 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) { System.out.println(firstNonRepeatingChar("aáa")); } }
The string "aáa" has characters: 'a', 'á', 'a'.
Counts: 'a' = 2, 'á' = 1.
The first character with count 1 is 'á' at index 1.
