Menu

1 / 2

LeetCode 387: First Unique Character in a String — Simple Explanation with Carry Logic (Java)

DEV Community·Jerin·6 months ago
#YRHYQ6EQ
#java#example#algorithm#leetcode#character
Reading 0:00
15s threshold

Difficulty : Easy

Topics : Hash Table, String, Queue, Counting

Platform : Leetcode

Problem Statement

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

Problem Statement Simplified

Get the index of the first non-repeating character, else return -1.

Mistakes and Learning

Do not blindly loop thorugh.

Do not just delete the duplicates, remove the duplicated character also.

Example 1

`Input: s = "leetcode"

Output: 0

Explanation:

The character 'l' at index 0 is the first character that does not occur at any other index.`

Example 2

`Input: s = "loveleetcode"

Output: 2`

Key Insight

Remove all the duplicating characters

Then get the first character

Get the first character index.

If no unique then -1.

Algorithm

Convert the string to a char array.

Intitialize a HashMap to store the character and the repeating counts.

Intitialize a for loop

Put the character in the HashMap with getOrDefault to check if the character already…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.