Given a string of characters, return the index of the first non-repeating character.
The problem wants use to find the FIRST NON-REPEATING
character in the string. The easiest way is to run two for loops and check if the ith
value repeats or not.
i to length
of the string.duplicate
variable and initialize it to false
.i+1 to length
.str[i] === str[j]
, this means we have encountered a duplicate, and this will not be our solution. We break from the loop from here. Assign duplicate = true
to signify that there is a duplicate for the current ith
value.str[i] !== str[j]
, keep on iterating and search for a duplicate.duplicate = true
duplicate = false
, return the index because this will be the first
time we encounter a non-duplicate value.null
if all the strings have duplicates.O(n^2)
- Because we iterate the string twice.O(1)
- Because there will be atmost 26 characters in the string.map
which will contain the frequencies of all the characters that appear in the string.increment by
, otherwise, initialize with 1
.map[str[i]] === 1
. This will check if the occurrence of the character is equal to one. Since we are traversing from left to right, the first one to be equal to 1
will be the first non-repeating character.O(n)
- Since we are iterating over the array twice, but separately.O(1)
- Because there will be atmost 26 characters in the string.