LeetCode //C - 387. First Unique Character in a String
387. First Unique Character in a String
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 . l e n g t h < = 1 0 5 1 <= s.length <= 10^5 1<=s.length<=105
- s consists of only lowercase English letters.
From: LeetCode
Link: 387. First Unique Character in a String
Solution:
Ideas:
1. Frequency Array: We use an array freq[26] to store the count of each character. Since there are only 26 lowercase English letters, we can map each character to an index (s[i] - ‘a’).
2. First Pass: We iterate through the string once and count how many times each character appears.
3. Second Pass: We iterate through the string again and check the frequency of each character. The first character with a frequency of 1 is the first unique character, and we return its index.
4. Edge Case: If no unique character is found, the function returns -1.
Code:
int firstUniqChar(char* s) {int freq[26] = {0}; // Array to store frequency of each character// First pass: count the frequency of each characterfor (int i = 0; s[i] != '\0'; i++) {freq[s[i] - 'a']++;}// Second pass: find the first character with frequency 1for (int i = 0; s[i] != '\0'; i++) {if (freq[s[i] - 'a'] == 1) {return i; // Return the index of the first unique character}}return -1; // If no unique character is found, return -1
}