0

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.

3
  • Have you looked at using Map? It retains the insertion order, so you could track how many of each letter exists, and then find the first one that only has one instance. Commented Nov 20, 2024 at 15:17
  • What large strings are you testing with? Commented Nov 20, 2024 at 15:27
  • 1
    @mykaf: I was posting an answer here, when it was (correctly) closed as a duplicate. I posted it over there, as I think it adds something to the large collection of answers. One of my approaches uses a Map in 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 my Map version, and didn't want to do some Map cloning for this simple problem, but the answer is there. Commented Nov 20, 2024 at 16:12

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.