First Unique Character in a String - Complete Solution Guide
First Unique Character in a String is LeetCode problem 387, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
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 . 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 <= 10 5 s consists of only lowercase English letters.
Detailed Explanation
The problem asks us to find the index of the first character in a given string that appears only once. If no such character exists, we should return -1. The string will only contain lowercase English letters, and its length will be between 1 and 100,000 characters inclusive. This means we can use a frequency counting approach efficiently.
Solution Approach
The solution involves using a hash table (or array for C) to count the occurrences of each character in the string. After counting the occurrences, we iterate through the string again. In this second pass, we check the count of each character. The first character encountered with a count of 1 is the first unique character, and its index is returned. If no character has a count of 1 after the second pass, it means no unique character exists, so -1 is returned.
Step-by-Step Algorithm
- Step 1: Initialize a hash table (or array) to store character counts. The keys are the characters and the values are their frequencies.
- Step 2: Iterate through the input string `s`. For each character, increment its count in the hash table.
- Step 3: Iterate through the input string `s` again. For each character at index `i`, check its count in the hash table.
- Step 4: If the count of the character at index `i` is 1, return `i`.
- Step 5: If the loop completes without finding any character with a count of 1, return -1.
Key Insights
- Insight 1: We need to keep track of the frequency of each character in the string.
- Insight 2: A hash table (or an array due to the constraint on character set) is suitable for storing the character counts.
- Insight 3: We need to iterate through the string twice. The first time to count character frequencies, and the second time to find the first character with a frequency of 1.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
Topics
This problem involves: Hash Table, String, Queue, Counting.
Companies
Asked at: EPAM Systems, Goldman Sachs, Ozon, PayPal, Qualcomm, ServiceNow, Walmart Labs, Yandex, Zoho, tcs.