πDay 4. Non-Repeating Character π§
The problem can be found at the following link: Problem Link
π‘ Problem Breakdown:
Given a string s consisting of lowercase Latin letters, return the first non-repeating character in s. If there is no non-repeating character, return '$'.
Note: When you return '$', the driver code will output -1.
π Example Walkthrough:
Input:
s = "geeksforgeeks"
Output:
'f'
Explanation:
In the given string, 'f' is the first character in the string which does not repeat.
Input:
s = "racecar"
Output:
'e'
Explanation:
In the given string, 'e' is the only character in the string which does not repeat.
Input:
s = "aabbccc"
Output:
-1
Explanation: All the characters in the given string are repeating.
Constraints:
$
1 <= s.size() <= 10^5$
π― My Approach:
Frequency Array Method:
Since the input consists only of lowercase Latin letters, a frequency array of size
26is sufficient to count occurrences of each character.Traverse the string once to update the frequency of each character in the array.
Traverse the string a second time to identify the first character with a frequency of
1.
Steps:
Initialize a frequency array
freq[26]and set all elements to0.For each character in the string, increment its corresponding frequency in the array.
Iterate through the string again, checking for the first character with a frequency of
1.If no such character exists, return
'$'.
π Time Complexity:
Expected Time Complexity: O(n), where
nis the size of the string. The algorithm requires two linear passes through the string.Expected Auxiliary Space Complexity: O(1), as the frequency array uses a fixed amount of additional space (
26elements).
π Solution Code
Code (C)
Code (Cpp)
Code (Java)
Code (Python)
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated