LeetCode WalkThru: 'First Unique Character in a String'
Tags: javascript, algorithms, datastructures, beginners
Published: 2021-12-28 21:34:06

Hi Programmers! 

Today we will be solving LeetCode's 'First Unique Character in a String'. Click [here](https://leetcode.com/problems/first-unique-character-in-a-string/) 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.
```

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
```

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 <strong>first</strong> 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
```

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:


```js
function firstUniqCharacter(s){

}
```

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

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

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 <strong>for loop</strong>.


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

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:

```js
let s = 'Cats'

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

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()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf) => _returns the first index at which a given element can be found in the string_
* [lastIndexOf()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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 <strong>equal</strong> its last index -- _because it only appears once!_ Let's code this out:


```js
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
      }
   }
}
```

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:

```js
let s = 'Pigeon'
console.log(s.indexOf('P')
console.log(s.lastIndexOf('P')
```
![pigeon](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0v8ods3qvxv8qyfh9qiq.png)

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.