LeetCode WalkThru: 'First Unique Character in a String'
Adriana DiPietro
Posted on December 28, 2021
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.
From this simple set of instructions, we can figure out a few things about what this challenge is asking of us:
- Input is a string
- Output is an integer (either the index of the non-repeating character or -1)
- There could be multiple non-repeating characters, but we must return the index of the first
- 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 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
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){
}
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
}
}
Cool -- the foundation is laid. Now we have to consider a few important goals:
- Check to see if non-repeating character exists
- 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
}
}
}
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'
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
}
}
}
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')
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:
- JavaScript index begins at 0.
- When you have to access every element in an array or string, iteration is your best friend.
- A **for loop **is a type of iterator.
- A for loop executes only while the condition is still true.
- The code block represents what will be executed on each string item while the condition is still true.
- Strings, like arrays in JavaScript, are indexed; each letter has its own index.
- JavaScript has so many built-in methods waiting to be used -- please utilize them!!!
- Keep your code readable AND scalable.
- Code in a way that makes sense to you.
- 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.
Posted on December 28, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.