DEV Community

Naya Willis
Naya Willis

Posted on

1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Instrument, monitor, fix: a hands-on debugging session

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️