First Non-Repeating Character
First Non-Repeating Character
First Non-Repeating Character
Problem Statement:
Given a string, return the index of the first character that appears only once. If no such character exists, return -1.
Example 1
Input:
s = "leetcode"Output:
0
Explanation:
Character 'l' appears only one time and its index is 0.
Example 2
Input:
s = "aabb"Output:
-1
Explanation:
All characters are repeating, so return -1.
Solution:
fun main() {
val s1 = "leetcode"
val s2 = "aabb"
println(findNonRepeatingChar(s1)) // 0
println(findNonRepeatingChar(s2)) // -1
}
fun findNonRepeatingChar(str: String): Int {
val freq = mutableMapOf<Char, Int>()
// Step 1: Count character frequency
for (i in 0 until str.length) {
val ch = str[i]
freq[ch] = (freq[ch] ?: 0) + 1
}
// Step 2: Find first character with frequency 1
for (i in 0 until str.length) {
val ch = str[i]
if (freq[ch] == 1) {
return i
}
}
return -1
}