Note: Write a solution that only iterates over the string once and uses O(1) additional memory, since this is what you would be asked to do during a real interview.
Given a string s, find and return the first instance of a non-repeating character in it. If there is no such character, return '_'
.
Examples 1--3 below pass all visible tests but fail due to timeout on very long strings. I am pretty sure this is because [x, ...xs]
is expensive, as is xs.shift()
. Example 4 doesn't time out, and the only difference between 3 and 4 is xs.shift()
has been replaced with xs.pop()
(and the input array has therefore been reversed to accomodate, which I thought would be prohibitively expensive but... 🤷♂️). A much more elegant solution is 5--no for
loops and no mutation 🙂--and I will never again try to replace reduce
with explicit recursion.