Implement the firstUniqueCharacterIndex method that returns the index of the first character that appears only once.

The input contains a string text. Your task is to return the index of the first character that appears exactly once in the string.

If every character appears more than once, return -1. Indexing starts from 0, so in leetcode, the character l is unique and appears at index 0.

Example 1

Input
text (string) = leetcode
Returns (int) 0

Example 2

Input
text (string) = loveleetcode
Returns (int) 2

Example 3

Input
text (string) = aabb
Returns (int) -1

Count how many times each character appears in the string.

After building the frequency map, scan the string again from left to right. The first position whose character has frequency 1 is the required answer.

If the second scan finishes without finding such a character, no unique character exists.

Pseudocode:

function firstUniqueCharacterIndex(text):
    frequency = empty map
    for each character ch in text:
        frequency[ch]++
    for i from 0 to length(text) - 1:
        if frequency[text[i]] == 1:
            return i
    return -1
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.