FrontendPro

14Check whether two strings are anagrams

easyAbout 15 minutesCodinghash-mapstrings

Problem

Implement isAnagram(s, t). Return true when t uses exactly the same characters as s, the same number of times, in any order.

isAnagram("anagram", "nagaram"); // true
isAnagram("rat", "car"); // false

Requirements

  • Comparison is case-sensitive: "Listen" and "silent" are not anagrams.
  • Work for any Unicode text, including emoji.
  • Solve it in O(n) time.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

solution.jsJavaScript

Press Run or ⌘ Enter to execute your code.

Video walkthrough

Stuck? Watch someone solve it, then try again on your own.

Valid Anagram - Leetcode 242 - PythonNeetCode on YouTubeOpen on YouTube

Step-by-step

Strings with different lengths can never be anagrams. This is an O(1) early exit.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 5 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever