Leetcode 387: First Unique Character in a String

grid47
grid47
Exploring patterns and algorithms
Sep 29, 2024 4 min read

A glowing string with the first unique character softly highlighted.
Solution to LeetCode 387: First Unique Character in a String Problem

Given a string s, find the index of the first character that does not repeat in the string. If all characters repeat, return -1.
Problem
Approach
Steps
Complexity
Input: The input consists of a string s.
Example: s = "programming"
Constraints:
• 1 <= s.length <= 10^5
• s consists of only lowercase English letters
Output: Return the index of the first non-repeating character, or -1 if no such character exists.
Example: Output: 0
Constraints:
• The index should be within the range of the string length.
Goal: The goal is to find the first non-repeating character efficiently.
Steps:
• Create a frequency map of characters in the string.
• Traverse the string and check the frequency of each character.
• Return the index of the first character with a frequency of 1.
Goal: The algorithm should run efficiently for large inputs.
Steps:
• The time complexity should be linear, O(n).
• Space complexity should be O(n) for the frequency map.
Assumptions:
• The input string is valid and contains only lowercase English letters.
Input: Input: "programming"
Explanation: The character 'p' at index 0 is the first non-repeating character in the string.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus