Solving Leetcode Interviews in Seconds with AI: First Unique Character in a String
Introduction
In this blog post, we will explore how to solve the LeetCode problem "387" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
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 <= 105 s consists of only lowercase English letters.
Explanation
Here's the solution to find the first non-repeating character in a string, explained and implemented efficiently:
- Character Counting: Use a hash map (dictionary in Python) to store the frequency of each character in the string.
- First Unique Character: Iterate through the string again. For each character, check its frequency in the hash map. If the frequency is 1, return its index.
Handle No Unique Character: If the loop completes without finding a unique character, return -1.
Runtime Complexity: O(n), where n is the length of the string.
- Storage Complexity: O(1), because the hash map will store at most 26 key-value pairs (lowercase English letters).
Code
def firstUniqChar(s: str) -> int:
"""
Finds the index of the first non-repeating character in a string.
Args:
s: The input string.
Returns:
The index of the first non-repeating character, or -1 if none exists.
"""
char_counts = {}
for char in s:
char_counts[char] = char_counts.get(char, 0) + 1
for i, char in enumerate(s):
if char_counts[char] == 1:
return i
return -1