First Unique Character Solution for Cognizant
Company: Cognizant · Difficulty: Easy · Topics: String, Hash Table, Counting
Problem Statement
Given a string s, find the first non-repeating character in it and return its index.
Examples
Example 1:
Input: s = "leetcode"
Output: 0
Explanation: The first non-repeating character is 'l' at index 0.
Example 2:
Input: s = "loveleetcode"
Output: 2
Explanation: The first non-repeating character is 'v' at index 2.
Approach
Use a hash table to count character frequencies, then scan the string to find the first character with count 1.
Time and Space Complexity
- Time Complexity: O(n)
- Space Complexity: O(k) where k is the number of unique characters