Algo-Sim › Arrays & Hashing

Valid Anagram

Easy · Arrays & Hashing · step through it in Java, Python and C++ on your own input

Is t a rearrangement of the letters of s? Count letters in a 26-slot frequency table.

Problem

Given two strings s and t, decide whether t uses exactly the same letters as s, each the same number of times, possibly in a different order. Return true or false.

Constraints

Edge cases to test

Follow-up questions

What if the input is Unicode, not just a–z?
Count with a hash map keyed by code point instead of a 26-slot array: O(n) time, O(k) space for k distinct characters.
Can you do it without the count table?
Sort both strings and compare: O(n log n) time, O(1) extra if sorting in place.

Solution

Java

public boolean isAnagram(String s, String t) {
    if (s.length() != t.length()) return false;
    int[] count = new int[26];
    for (int i = 0; i < s.length(); i++) {
        count[s.charAt(i) - 'a']++;
        count[t.charAt(i) - 'a']--;
    }
    for (int c : count) {
        if (c != 0) return false;
    }
    return true;
}

Python

def is_anagram(s, t):
    if len(s) != len(t):
        return False
    count = [0] * 26
    for i in range(len(s)):
        count[ord(s[i]) - ord('a')] += 1
        count[ord(t[i]) - ord('a')] -= 1
    for c in count:
        if c != 0:
            return False
    return True

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool isAnagram(string &s, string &t) {
        if (int(s.size()) != int(t.size()))
            return false;
        vector<int> count = vector<int>(26);
        for (int i = 0; i < int(s.size()); i++) {
            count[s[i] - 'a']++;
            count[t[i] - 'a']--;
        }
        for (int c : count) {
            if (c != 0)
                return false;
        }
        return true;
    }
};

More Arrays & Hashing problems