Skip to content
PlaceNivo

Strings Easy

Valid Anagram: Solution and Approach

Return true if string t is an anagram of string s, meaning both use exactly the same letters the same number of times.

Similar questions reported in: TCS, Wipro, Accenture, Capgemini, Cognizant

Example

Input:
s = "anagram", t = "nagaram"
Output:
true

Brute force first

Sort both strings and compare them. This is O(n log n).

The better idea

Count the letters. Add 1 for each letter in s and subtract 1 for each letter in t. If every count ends at 0, the strings are anagrams.

Steps

  1. If the lengths differ, return false.
  2. Make an array of 26 counts (for lowercase letters a to z).
  3. For each index i: count[s[i]] += 1 and count[t[i]] -= 1.
  4. Return true only if every count is 0.

Code

def is_anagram(s, t):
    if len(s) != len(t):
        return False
    count = [0] * 26
    for a, b in zip(s, t):
        count[ord(a) - ord("a")] += 1
        count[ord(b) - ord("a")] -= 1
    return all(c == 0 for c in count)

Complexity

Time: O(n)

Space: O(1): the array always has 26 slots.

Edge cases to test

  • Different lengths: return false right away.
  • For Unicode input, use a hash map instead of a 26-slot array.

Solved it? Pick the next problem

Do one more problem from the same pattern today, so the idea sticks.