Back to Browse

39.Check If Two Strings Are Anagrams in Python | Core Coding Interview Question

39 views
Sep 3, 2025
10:31

In this tutorial, you’ll learn how to check if two strings are anagrams in Python without using inbuilt shortcuts like sorted() or Counter. 👉 What you’ll learn: What an anagram is Step-by-step coding explanation Interview-friendly manual solution Real-life applications of anagram checking 💡 This is a must-know Python concept for coding interviews and competitive programming. 🔔 Subscribe for more Python & DSA tutorials! for ch in str1: freq1[ch] = freq1.get(ch, 0) + 1 for ch in str2: freq2[ch] = freq2.get(ch, 0) + 1 1. Iterating over each character for ch in str1: This loop goes through every character (ch) in the string str1. Example: if str1 = "listen", the loop will visit 'l', 'i', 's', 't', 'e', 'n'. freq1[ch] = freq1.get(ch, 0) + 1 freq1 is a dictionary that keeps track of how many times each character appears. .get(ch, 0) → tries to get the current count of character ch in the dictionary. If ch is not already present, it returns 0 (default value). Then + 1 adds one occurrence. Finally, it stores the updated count back into freq1[ch]. Example with "listen": Iteration Character ch freq1 after update 1 'l' {'l': 1} 2 'i' {'l': 1, 'i': 1} 3 's' {'l': 1, 'i': 1, 's': 1} 4 't' {'l': 1, 'i': 1, 's': 1, 't': 1} 5 'e' {'l': 1, 'i': 1, 's': 1, 't': 1, 'e': 1} 6 'n' {'l': 1, 'i': 1, 's': 1, 't': 1, 'e': 1, 'n': 1} for ch in str2: freq2[ch] = freq2.get(ch, 0) + 1 This builds another dictionary freq2 for the second string.

Download

0 formats

No download links available.