Day 2: First Non-Repeating Character – 100 Days of DSA Challenge 🚀

Day 2: First Non-Repeating Character – 100 Days of DSA Challenge 🚀

Problem:

Today’s challenge is to find the first non-repeating character in a string.

Input:   "leetcode"
Output:   0 (index of the first non-repeating character 'l')        

Solution Approach:

The key is to count the occurrences of each character in the string. Then, we traverse the string a second time to identify the first character that appears only once.

Here’s the algorithm and Python code:


Algorithm: First Non-Repeating Character

  1. Input: A string s.
  2. Process:Use a dictionary (hash map) to store the frequency of each character.Traverse the string again to find the first character with a frequency of 1.
  3. Output: Return the index of the first non-repeating character, or -1 if none exists.


def first_non_repeating_char(s):
    # Step 1: Create a frequency dictionary
    char_count = {}
    
    for char in s:
        if char in char_count:
            char_count[char] += 1
        else:
            char_count[char] = 1
    
    # Step 2: Find the first character with a count of 1
    for index, char in enumerate(s):
        if char_count[char] == 1:
            return index
    
    return -1  # If no non-repeating character is found

# Test the function
input_str = "leetcode"
output_index = first_non_repeating_char(input_str)
print("Input:", input_str)
print("Output:", output_index)        

Key Insights:

  • Hash maps (dictionaries) allow efficient frequency counting with constant time lookups.
  • By iterating twice (once to count, once to find), we maintain an efficient O(n) time complexity.
  • Handling edge cases, such as when all characters repeat, ensures robust code.


Let’s keep the momentum going! Join me tomorrow for Day 3. Let me know if you have any feedback or want to share your solutions!

#100DaysOfDSA #Day2 #ProblemSolving #Python #Algorithms #LearningInPublic

To view or add a comment, sign in

More articles by MOHAMED ARSHAD

Insights from the community

Others also viewed

Explore topics