Check if Two Strings Are Anagrams

Problem

Check whether two strings are anagrams of each other (same characters, same frequencies).

Input:  s = "listen", t = "silent"
Output: true

Python Solution

def is_anagram(s, t):
    if len(s) != len(t):
        return False
    counts = {}
    for ch in s:
        counts[ch] = counts.get(ch, 0) + 1
    for ch in t:
        if ch not in counts:
            return False
        counts[ch] -= 1
        if counts[ch] == 0:
            del counts[ch]
    return not counts

C++ Solution

bool isAnagram(string s, string t) {
    if (s.size() != t.size()) return false;
    unordered_map<char, int> counts;
    for (char ch : s) counts[ch]++;
    for (char ch : t) {
        if (--counts[ch] < 0) return false;
    }
    return true;
}

Java Solution

class Solution {
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) return false;
        int[] counts = new int[26];
        for (char ch : s.toCharArray()) counts[ch - 'a']++;
        for (char ch : t.toCharArray()) {
            if (--counts[ch - 'a'] < 0) return false;
        }
        return true;
    }
}

Complexity

Time: O(n) — each string is scanned once to build and then consume the frequency counts. Space: O(1) for lowercase-only input (fixed 26-slot array), or O(k) for k distinct characters with a hash map.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.