CodeLog
Blog

Solving problem: First Unique Character

Table of Contents


What is the First Unique Character problem


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.

Examples



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

Breaking down


This approach includes breaking down complex problem in to smaller and smaller sub-problems. For example — You want to watch movie in theater.

  • Book a ticket
  • You will go the theater
  • Need to pass the security check
  • Need to show your booking ticket at the counter
  • so on...

 

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


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.

Solving Problem: First Unique Character

  • Looping through all the characters in the string.
  • Checking if the character already exists in the hash.
    • then — removing it from the hash and adding it to duplicate hash.
    • else   — add current index to hash with the key as character

Solution



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;
};

 

🔝 Go To Beginning 🔝

Copyright © 2023. codelog.dev