Non Repeating First Character

Given a string of characters, return the index of the first non-repeating character.

Brute Force Approach

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.

  1. Run a for loop from i to length of the string.
  2. Declare a duplicate variable and initialize it to false.
  3. Run another for loop which is nested, from i+1 to length.
  4. If 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.
  5. If str[i] !== str[j], keep on iterating and search for a duplicate.
  6. At the end of the inner for loop execution, check if duplicate = true
  7. If duplicate = false, return the index because this will be the first time we encounter a non-duplicate value.
  8. Return null if all the strings have duplicates.

Time complexity

  • O(n^2) - Because we iterate the string twice.

Space complexity

  • O(1) - Because there will be atmost 26 characters in the string.

Hash Map Approach

  1. Declare an object map which will contain the frequencies of all the characters that appear in the string.
  2. For creating the map, run a for loop over the string. If the character is there in the string, increment by , otherwise, initialize with 1.
  3. Iterate over the string again and check if 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.
  4. Return null if the for loop doesnt return anything.

Time complexity

  • O(n) - Since we are iterating over the array twice, but separately.

Space complexity

  • O(1) - Because there will be atmost 26 characters in the string.
Solve Non Repeating First Character on Algochurn

Practice all the solutions below

Practice the most popular front-end questions asked in coding interviews with   Frontend Churn