Taro Logo

First Unique Character in a String

#22 Most AskedEasy
Topics:
ArraysStrings

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

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

Example 3:

Input: s = "aabb"

Output: -1

Constraints:

  • 1 <= s.length <= 105
  • s consists of only lowercase English letters.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What character set should we expect in the string? For example, is it restricted to lowercase English letters (a-z), or can it include uppercase letters, digits, whitespace, or full Unicode/ASCII characters?
  2. How should we handle an empty string or an input consisting entirely of repeating characters? Should the function return -1 in both cases?
  3. Are uppercase and lowercase characters considered distinct (case-sensitive), or should 'A' and 'a' be treated as the same character?
  4. Is the memory footprint a primary concern, or can we allocate auxiliary space proportional to the character set size?
  5. If the input string is extremely large (e.g., gigabytes in size), should we expect it to be streamed or fit entirely in memory?

Brute Force Solution

Approach

Imagine you are looking for the first person in a line who has a unique hat that no one else is wearing. The brute force approach involves taking each person one by one and checking the entire rest of the line to see if anyone else is wearing the exact same hat.

Here's how the algorithm would work step-by-step:

  1. Begin with the very first character in the text.
  2. Look through the rest of the text to see if that exact same character appears anywhere else.
  3. If you find a match elsewhere, that character is not unique, so you must abandon it and move on.
  4. If you check the entire rest of the text and find no other copies of that character, you have found your answer.
  5. If the first character turned out to be a duplicate, repeat the entire checking process for the second character.
  6. Keep testing each character one by one in this exhaustive manner until you find one that never appears again anywhere else in the text.
  7. If you test every single character and every single one of them has a duplicate somewhere else, conclude that there are no unique characters at all.

Code Implementation

def first_uniq_char(text_string):
    # Iterate through each character to test if it appears anywhere else in the string
    for current_index in range(len(text_string)):
        current_char = text_string[current_index]
        is_duplicate_found = False

        for comparison_index in range(len(text_string)):
            if current_index != comparison_index and text_string[comparison_index] == current_char:
                is_duplicate_found = True
                break

        # Stop and return the index immediately when we find a character with no duplicates
        if not is_duplicate_found:
            return current_index

    # Return negative one if every character in the string has at least one duplicate
    return -1

Big(O) Analysis

Time Complexity
–
Space Complexity
O(1) – The brute force approach described relies entirely on nested loops to compare characters in place without creating any auxiliary data structures, lists, or hash maps. The extra memory usage consists only of a few primitive integer variables used for loop indices. Therefore, the auxiliary space remains constant regardless of the input size N, resulting in an optimal space complexity.

Optimal Solution

Approach

To quickly find the very first letter that does not repeat, we can use a two-pass strategy. Instead of constantly checking and re-checking letters against each other, we first gather a quick count of how many times each letter appears.

Here's how the algorithm would work step-by-step:

  1. Go through the entire message from beginning to end and keep a tally of how many times every single letter shows up.
  2. Once you have the total counts for all the letters, go back to the beginning of the message and look at each letter in order.
  3. Ask the tally sheet if the letter you are currently looking at appeared only once.
  4. Stop at the very first letter where the answer is yes and point to it as your winner.
  5. If you finish checking all the letters and none of them have a count of just one, conclude that there are no unique letters at all.

Code Implementation

def first_uniq_char(input_string):
    character_tally = {}

    # We build a frequency map first to know the total count of every character in constant time.
    for current_character in input_string:
        if current_character in character_tally:
            character_tally[current_character] += 1
        else:
            character_tally[current_character] = 1

    # A second pass in original order is required because we need the lowest index, not lowest frequency.
    for index_position, current_character in enumerate(input_string):
        if character_tally[current_character] == 1:
            return index_position

    # Returning negative one guarantees we signal the absence of any non-repeating characters.
    return -1

Big(O) Analysis

Time Complexity
O(n) – The cost is driven by the length of the input string, which we will call n. In the first pass, we iterate through all n characters of the string to build a frequency tally in a hash map. In the second pass, we iterate through the n characters of the string again from the beginning to find the first one with a count of one. Because hash map lookups take constant time, these two sequential passes perform roughly 2n operations total. Dropping the constant factor gives us a final Big O time complexity of O(n).
Space Complexity
O(1) – The auxiliary space is driven by the tally sheet used to store the frequency of each character. Since the input string consists of standard ASCII or lowercase English letters, the hash map or frequency array requires at most a constant number of entries, 26, regardless of the input length N. Therefore, the extra memory usage remains strictly bounded and does not grow with N.

Edge Cases

Empty string input
How to Handle:
Return -1 immediately since no characters exist to evaluate.
String with a single character
How to Handle:
Return index 0 because a single character is inherently unique.
All characters in the string are repeating
How to Handle:
Return -1 as the frequency map will show no count equals one.
String with all unique characters
How to Handle:
Return index 0 because the very first character is the first unique one.
Very large string exceeding standard memory limits
How to Handle:
Use a fixed-size frequency array of size 26 for lowercase English letters to maintain O(1) space complexity.
String containing uppercase, special, or unicode characters
How to Handle:
Use a hash map instead of a fixed array to safely track counts for any character set without out-of-bounds errors.
First unique character appears late in a very long string
How to Handle:
Use a two-pass approach where the second pass iterates through the original string indices to find the first character with a count of one.
0/245 completed