The Secret Twins

An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
easy
Seniority
L3
Asked in
Nielsen

Problem

Given two strings s1 and s2, return True if they are anagrams (same character multiset). Comparison is case-insensitive (treat 'A' and 'a' as equal).

Same letters, different disguises.

Example 1

Input:

s1 = "listen", s2 = "silent"

Output:

true

Example 2

Input:

s1 = "hello", s2 = "world"

Output:

false

Worked solution and explanation

Why this problem exists in real interviews

This tests string manipulation, frequency counting with dicts, and case normalization. Interviewers use it to see if a candidate handles character counting cleanly without reaching for sorted-string shortcuts that hide understanding.


Break down the requirements

Step 1: Normalize both strings to lowercase

Case-insensitive comparison means 'Listen' and 'Silent' should match. Convert both inputs with .lower() before counting.

Step 2: Count character frequencies for each string

Build a frequency dict for each string by iterating character by character. Two strings are anagrams only if their frequency maps are identical.

Step 3: Compare the two frequency dicts

If the dicts are equal, return True. Python dict equality checks both keys and values, so this is a single comparison.


The solution

Frequency map comparison
def is_anagram(s1: str, s2: str) -> bool:
    s1 = s1.lower()
    s2 = s2.lower()
    if len(s1) != len(s2):
        return False
    freq1 = {}
    for ch in s1:
        freq1[ch] = freq1.get(ch, 0) + 1
    freq2 = {}
    for ch in s2:
        freq2[ch] = freq2.get(ch, 0) + 1
    result = freq1 == freq2
    return result

Common follow-up questions