LeetCode 387: First Unique Character in a String Solution
Master LeetCode problem 387 (First Unique Character in a String), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
387. First Unique Character in a String
Problem Explanation
Explanation
To solve this problem, we can iterate through the input string s and store the frequency of each character in a HashMap. Then we iterate through s again to find the first character with a frequency of 1 in the HashMap, which will be our answer.
- Time complexity: O(n) where n is the length of the input string
s - Space complexity: O(1) since the size of the HashMap is limited by the number of lowercase English letters
Solution Code
class Solution {
public int firstUniqChar(String s) {
Map<Character, Integer> freq = new HashMap<>();
for (char c : s.toCharArray()) {
freq.put(c, freq.getOrDefault(c, 0) + 1);
}
for (int i = 0; i < s.length(); i++) {
if (freq.get(s.charAt(i)) == 1) {
return i;
}
}
return -1;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 387 (First Unique Character in a String)?
This page provides optimized solutions for LeetCode problem 387 (First Unique Character in a String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 387 (First Unique Character in a String)?
The time complexity for LeetCode 387 (First Unique Character in a String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 387 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 387 in Java, C++, or Python.