DEV Community

Naya Willis
Naya Willis

Posted on

Leetcode: First Unique Char

Overview

Today I will be solving the First Uniq Char leetcode challenge. The instructions are as follows.

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

const firstUniqChar = s => {
    // code goes here
};
Enter fullscreen mode Exit fullscreen mode

Step 1

I started off with a for loop to loop through str.

const firstUniqChar = str => {
     //
}
Enter fullscreen mode Exit fullscreen mode

Step 2

For each character in the string I get the index of it by using the method

str.indexOf(i => current index)

. Obviously on the first go round it will be the 0th index.

Step 3

I created a if block to check if the letter at index of i has a second appearance within the string by using str.lastIndexOf(i => current index). Within that if conditional

if str.indexOf(i) is === to str.lastIndexOf(i)

. There might be a chance that there are 4 occurrences of that letter and lastIndexOf doesn't count occurrences. But, it is good enough to find out if at least there is a repeat within the string.

So going back to the conditional,

str.indexOf(i) is === to str.lastIndexOf(i)

. If both str.indexOf(i) and str.lastIndexOf(i) are the same indices then we know that, that letter isn't a repeat letter and then we'll return it.

if(s.indexOf(s.charAt(i)) === s.lastIndexOf(s.charAt(i))){ 
     return i 
}
Enter fullscreen mode Exit fullscreen mode

In the event that there isn't a uniq char then we will just return -1

All Together

const firstUniqChar = s => {
    for(let i = 0; i < s.length; i++){
        if(s.indexOf(s.charAt(i)) === s.lastIndexOf(s.charAt(i))){ 
             return i 
        }
    }
    return -1
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)