Space Complexity: O(n + m)
1️⃣8️⃣9️⃣ How Do You Check if Two Strings are Anagrams?
Answer:
Two strings are anagrams if they contain the same characters with the same frequencies, but possibly in a different order.
Example:
"listen" → "silent"
Both contain the same characters, so they are anagrams.
Python:
str1 = "listen"
str2 = "silent"
if sorted(str1) == sorted(str2):
print("Anagrams")
else:
print("Not Anagrams")
Time Complexity: O(n log n)
A frequency-count approach can achieve O(n) average time.
1️⃣9️⃣0️⃣ How Do You Find the First Non-Repeating Character?
Answer:
Count the frequency of every character, then scan the string again and return the first character whose frequency is "1".
Example:
Input: "swiss"
Output: "w"
Python:
from collections import Counter
text = "swiss"
count = Counter(text)
for char in text:
if count[char] == 1:
print(char)
break
Time Complexity: O(n)
Space Complexity: O(k), where "k" is the number of distinct characters.
🔥 Double Tap ❤️ For Part-20