So I tried looking for this in the search but the closest I could come is a similar answer in several different languages, I would like to use Javascript to do it.
T
We can keep track of frequency of each character of the string in an object. For example : for "aabcbd" we can store the frequency as
{ "a":2, "b":2, "c":1, "d":1 }
This will take O(n) time. Then we can traverse over this object and find the first character with frequency 1, which will also take O(n) time. So, the time complexity for this approach will be O(n).
const firstNonRepeating=(str)=>{
const obj={};
str.split("").forEach(item=>{
obj[item]
? obj[item]++
: obj[item]=1;
});
const item = Object.keys(obj).find(key=> obj[key] === 1);
return item;
}
Note: I use ES6 Object.keys method which may not work in older browsers.