I am trying to solve a common problem in data structures and algorithms (DSA): finding the first non-repeating character in a string using JavaScript. The function should iterate through the string and return the first character that does not repeat. If no such character exists, it should return null.
For example:
findFirstNonRepeatingChar("swiss"); // Output: "w"
findFirstNonRepeatingChar("aabbcc"); // Output: null
I attempted to solve this by looping through the string twice using nested for loops, checking each character against the others. However, this approach seems inefficient for long strings, as its time complexity is O(n²).
I was expecting to find a more optimized solution, possibly using a data structure like a hash map to reduce the time complexity to O(n), but I couldn't come up with the implementation.
Here’s what I have so far:
function findFirstNonRepeatingChar(str) {
for (let i = 0; i < str.length; i++) {
let isUnique = true;
for (let j = 0; j < str.length; j++) {
if (i !== j && str[i] === str[j]) {
isUnique = false;
break;
}
}
if (isUnique) {
return str[i];
}
}
return null;
}
This works for small inputs, but it becomes very slow for large strings. I would appreciate guidance on how to optimize this solution.
Mapin this way, and explains why a plain object doesn't work here. I end up preferring a different technique, because I don't like the mutation involved in myMapversion, and didn't want to do someMapcloning for this simple problem, but the answer is there.