This article is another part of a series on leet code problems solutions, and it provides a solution to the leet code problem number 387. This is a Leet code problem named First Unique Character in a String. We will solve it using python and it is the best space and time-optimized solution.
Question of 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
.
Explanation
If a character only appears once in the string, it is considered to be non-repeating. Finding the frequency of each character in the string and determining which character has a unit frequency are the next steps in locating such characters. A hash map, which maps characters to their corresponding frequencies and allows us to simultaneously update the frequency of each character we encounter in constant time, is an effective tool for doing this task.
Example
Example 1
Input: s = "leetcode"
Output: 0
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.
Approach to solve First Unique Character in a String
To solve this problem we simply traverse the string once and create two hashmaps. In the first hashmap, we store only the unique characters. In the second hashmap, we store the character when it occurs the first time. The only difference between both the hashmap is that in the first hashmap we will pop the element when it comes again.
Algorithm
This method performs the following steps for a given input array:
- Create hashmap variable first_unique to store element when it occurs the first time.
- string_elem hashmap to store all visited elements once.
- Run for loop to iterate over all elements of a string.
- Check if the character is visited once or not.
- If not visited then add it in both hashmaps.
- Check if the element is in a unique hashmap.
- If present then pop it.
- End For
- If there is a unique element then return its position.
- otherwise return -1
Python Code for First Unique Character in a String
class Solution:
def firstUniqChar(self, s: str) -> int:
#hashmap to store element when it occurs first time
first_unique={}
#hashmap to store all visited elements once
string_elem={}
#in both the hashmap we will use character and position as a key value pair
#iterate through all characters
for i in range(len(s)):
#check if character is visited once or not
if s[i] not in string_elem:
#if not visited then add it in both hashmap
first_unique[s[i]] = i
string_elem[s[i]] = i
#check if element is in unique hashmap
elif s[i] in first_unique:
#if present then remove it
first_unique.pop(s[i])
#if there is unique element then return its position
if(len(first_unique)>0):
res = list(first_unique.keys())[0]
return first_unique[res]
#otherwise return -1
else:
return -1
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(n)
Related Posts:
- Find Pivot Index (Leet Code-724)
- Spiral Matrix Problem Solution
- Isomorphic Strings
- Two Sum IV - Input is a BST (Leet Code-653)
- Search in a Binary Search Tree (Leet Code-700)
- Invert Binary Tree (Leet Code-266)
- Symmetric Tree (Leet Code-101)
- Maximum Depth of Binary Tree (Leet Code-104)
- Binary Tree Postorder Traversal (Leet Code-145)
- Binary Tree Inorder Traversal (Leet Code - 94)
- Binary Tree Pre-Order Traversal
- Binary Tree Level Order Traversal (Leet Code-102)
- Valid Parentheses (Leet Code-20)
- Remove Duplicates from Sorted List (Leet Code-83)
- Reverse Linked List (Leet code -206)
- Remove Linked List Elements (Leet Code-203)
- Merge Two Sorted Lists (Leet code-21)
- Ransom Note (Leet code-383)
- Valid Sudoku (Leet Code-36)
- Search a 2D Matrix (Leet Code-74)
- Linked List Cycle (Leet Code-141)
- Pascal's Triangle (Leet Code - 118)
- Reshape the Matrix (Leet Code-566)
- Best Time to Buy and Sell Stock (Leet code-121)
- The Intersection of Two Arrays II (Leet Code)
- Binary Search - Leet Code
- Two Sum - Leet Code