It is a coding challenge that requires find the first non-repeating character in the string. If there are no unique characters in the string then you need to return -1
.
INPUT:
s = "helloworld"
OUTPUT: 0
INPUT:
s = "happybirthday"
OUTPUT: 5
Explanation: The unique characters in the string happybirthday
are b, i, r, t
and d
, rest all remaning characters h, a, p
and y
are non-unique characters. The problem says we have to return the index of the first non-repeating character. In this case, the first non-repeating character is b
and its index is 5
.
h => 0
a => 1
p => 2
p => 3
y => 4
b => 5
This approach includes breaking down complex problem in to smaller and smaller sub-problems. For example — You want to watch movie in theater.
The benefit of using this approach is that you get a clear and better understanding of the question. Its obvious, it you know the question better you can come up with a better and efficient solution for the problem.
Visual Representation is another way of finding solution to the problem. Let's take a look how to find First Unique Character in the string.
duplicate
hash.var firstUniqChar = function (s) {
const del = {};
const hash = {};
for (let i = 0; i < s.length; i++) {
let k = s[i];
if (hash[k] != undefined) {
del[k] = i;
delete hash[k];
}
if (del[k] != undefined) {
continue;
}
hash[k] = i;
}
return hash[Object.keys(hash)[0]] ?? -1;
};
Copyright © 2023. codelog.dev