DEV Community

Cover image for LeetCode WalkThru: 'First Unique Character in a String'
Adriana DiPietro
Adriana DiPietro

Posted on • Edited on

LeetCode WalkThru: 'First Unique Character in a String'

Hi Programmers!

Today we will be solving LeetCode's 'First Unique Character in a String'. Click here to pull up the challenge on your end and let's get started!


Instructions

LeetCode provides these instructions:



Given a string 's', find the first non-repeating character in it and return its index. If it does not exist, return -1.

* 's' consists of only lowercase English letters.


Enter fullscreen mode Exit fullscreen mode

From this simple set of instructions, we can figure out a few things about what this challenge is asking of us:

  1. Input is a string
  2. Output is an integer (either the index of the non-repeating character or -1)
  3. There could be multiple non-repeating characters, but we must return the index of the first
  4. And lastly, the non-repeating character must be an a letter a-z (no numbers, symbols)

Examples

Let's look at some of the examples LeetCode provides:



Example 1:

Input: s = "leetcode"
Output: 0


Enter fullscreen mode Exit fullscreen mode

Where the input is 's' assigned to the string 'leetcode', the index of 0 is returned as the output. Why? The index 0, represents the first character of the string 'l'. The letter 'l' is the first non-repeating character in the string. As you can see, there are other non-repeating characters, such as 't', 'c', 'o' and 'd'. However, we only care about the first non-repeating character for this challenge.

Let's look at example where no letters of a string are non-repeating:



Example 3:

Input: s = "aabb"
Output: -1


Enter fullscreen mode Exit fullscreen mode

Here, we are given an output of '-1'. The string s provides no non-repeating characters, so according to the instructions, we return the integer of '-1'.

Seems simple enough right? Let's try to code this out.


Approach + Solution

We will start by declaring a function called 'firstUniqCharacter()' which will take in 's' representing a string:



function firstUniqCharacter(s){

}


Enter fullscreen mode Exit fullscreen mode

Now, we will build the foundation of an if-else statement because at this point we know if there are no non-repeating characters, we must return '-1':



function firstUniqCharacter(s){
    if(*/non-repeating character exists/*){
       // do something here
    } else {
      return -1
    }
}


Enter fullscreen mode Exit fullscreen mode

Cool -- the foundation is laid. Now we have to consider a few important goals:

  1. Check to see if non-repeating character exists
  2. Retrieve the index of the non-repeating character

Given a string, that we must comb through to check for something specific, iteration is our best bet. Let's utilize a for loop.



function firstUniqCharacter(s){
   for (let i = 0; i < s.length; i++){
      if(*/non-repeating character exists/*){
         // do something here
      } else {
        return -1
      }
   }
}


Enter fullscreen mode Exit fullscreen mode

A for loop basically says "while i is less than our input's length, continue to iterate and execute what is in the code block." The code block is represented by what is between the curly braces of our for loop. The 'i' represents the index of each letter of the string. So we can assume that 's[i]' equates to the value at that index. Let's see this in action:



let s = 'Cats'

console.log(s[0]) // => 'C'
console.log(s[1]) // => 'a'
console.log(s[2]) // => 't'
console.log(s[3]) // => 's'


Enter fullscreen mode Exit fullscreen mode

Now that we have this in mind, we can use the index of each letter of the string to our advantage.

JavaScript has some great built-in methods regarding the indices of a string. For today's reasons, we will utilize indexOf() and lastIndexOf().

  • indexOf() => returns the first index at which a given element can be found in the string
  • lastIndexOf() => returns the last index at which a given element can be found in the string

We know that for a character to be unique, its first index must equal its last index -- because it only appears once! Let's code this out:



function firstUniqCharacter(s){
   for (let i = 0; i < s.length; i++){
      if(s.indexOf(s[i]) === s.lastIndexOf(s[i])){
         // return the index of that unique character
         return i 
      } else {
        return -1
      }
   }
}


Enter fullscreen mode Exit fullscreen mode

In our if statement, our condition states "if the index of a character in the given string equals the last known index of that character, it must be unique". Then inside the code block, we return 'i' which is the index at which that unique character occurs.

Try this out in your console:



let s = 'Pigeon'
console.log(s.indexOf('P')
console.log(s.lastIndexOf('P')


Enter fullscreen mode Exit fullscreen mode

pigeon

Nice! This checks out.

We found a great solution that not only works, but is readable AND scalable.


Testing Our Code

Here are some examples you can try in your console:

let s = 'yyyyyyyyyyk'
let s = 'ello there'
let s = 'abcdefghijklmnop'
let s = 'aaamyyj'


Recap + Summary

Today we discovered a bunch of really great stuff that will help with our journey to becoming coding masters:

  1. JavaScript index begins at 0.
  2. When you have to access every element in an array or string, iteration is your best friend.
  3. A **for loop **is a type of iterator.
  4. A for loop executes only while the condition is still true.
  5. The code block represents what will be executed on each string item while the condition is still true.
  6. Strings, like arrays in JavaScript, are indexed; each letter has its own index.
  7. JavaScript has so many built-in methods waiting to be used -- please utilize them!!!
  8. Keep your code readable AND scalable.
  9. Code in a way that makes sense to you.
  10. Write notes or comments above your lines of code explaining what the code is doing.

Thank you for coding along with me :)
Please feel free to like, follow, and share.
Likewise, feel free to ask questions & leave comments or suggestions.

Top comments (3)

Collapse
 
shubhamb profile image
Shubham_Baghel

This is really nice post with great explanation,but code seems some issue here you can find updated working code of it

 for (i=0; i < s.length; i++) {
      if (s.indexOf(s[i]) == s.lastIndexOf(s[i])) {
        return i
      }
    }
   return -1
Enter fullscreen mode Exit fullscreen mode
Collapse
 
shock451 profile image
Abdullahi Ayobami Oladosu • Edited

Nice post! However, there are some issues with the snippet of code.
It does not pass some of the tests you provided.

Did you mean to return -1 after the loop rather than within the else block?

I would also like to add that you could iterate over unique letters rather than the full string to avoid repeating computations since the time complexity of indexOf is O(n) in the worst case.

let s = "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef";
const uniqueLetters = [...new Set(s)]; // "ef"
for (let i = 0; i < uniqueLetters.length; i++) {
...

Collapse
 
akib profile image
Shuaib hasan akib

Solution isn't working.