Sulba
000 / 100

Valid Anagram

EasyTime O(n)Space O(1)LeetCode 242 ↗

The problem

Given two strings s and t, return true if t is an anagram of s — the same letters, each used the same number of times, possibly in a different order — and false otherwise.

Examples

01
Input
s = "anagram", t = "nagaram"
Output
true
02
Input
s = "rat", t = "car"
Output
false

Constraints

  • 1 ≤ s.length, t.length ≤ 5 × 10⁴
  • s and t contain only lowercase English letters.

The idea

Order does not matter, only how many of each letter there are. So count.

Keep 26 counters, one per letter. Walk both strings together: each letter of s adds one to its counter, each letter of t takes one away. If the strings are anagrams, every counter ends back at zero. (Different lengths can be ruled out at once.)

Time
O(n) — one pass over both strings
Space
O(1) — always exactly 26 counters

Solution · every language run against every case

class Solution:    def isAnagram(self, s: str, t: str) -> bool:        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)