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:
Recommended by LinkedIn
Algorithm: First Non-Repeating Character
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:
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