First Unique Character in a String
2 min readJan 31, 2021
Step 1:
First you want to make a map with the key as the character and index as number of time the character occurs.
var charCount = new Map();for(var i = 0; i < s.length; i++){
var ch = s[i]; // get character //check if char exists in map & inc count on occurrence
if(charCount[ch]){
charCount[ch]++;
}else charCount[ch]= 1
}
Step 2 :
Then, loop through the string again and reference the “charCount” map to check if it is a repeating ( > 1) or non repeating (1) occurrence. The first character to have 1 as the char count value is the “First Unique Character”
for(var i = 0; i < s.length; i++){
//find the first letter with a charCount of 1 (non repeating)
var ch = s[i];
if(charCount[ch] == 1){
return i;
}
};
return -1;
Return index if character if found. Return -1 if not found or empty string.
Full code:
var firstUniqChar = function(s) {
var charCount = new Map();
for(var i = 0; i < s.length; i++){
var ch = s[i];
if(charCount[ch]){
charCount[ch]++
}else charCount[ch]= 1
} for(var i = 0; i < s.length; i++){
//find the first letter with a charCount of 1 (non repeating)
var ch = s[i];
if(charCount[ch] == 1){
return i;
}
};
return -1;
};
Time complexity -> O(n)
Space complexity -> O(n)
Problem: https://leetcode.com/problems/first-unique-character-in-a-string/