LeetCode Entry
387. First Unique Character in a String
First non-repeating char position.
387. First Unique Character in a String easy
blog post
substack
youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/496
Problem TLDR
First non-repeating char position.
Intuition
Compute char’s frequencies, then find first of 1.
Approach
Let’s try to make code shorter: Kotlin:
- groupBy
- run
- indexOfFirst Rust:
- vec![]
- String.find
- map_or
Complexity
-
Time complexity: \(O(n)\)
-
Space complexity: \(O(1)\)
Code
fun firstUniqChar(s: String) = s.groupBy { it }
.run { s.indexOfFirst { this[it]!!.size < 2 } }
pub fn first_uniq_char(s: String) -> i32 {
let mut f = vec![0; 128];
for b in s.bytes() { f[b as usize] += 1 }
s.find(|c| f[c as usize] < 2).map_or(-1, |i| i as i32)
}