DSA AnimatorREVISION VIDEOS
← Back to problems
New

Valid Anagram — LeetCode 242 video explanation

You get two strings, s and t. Return true if t is an anagram of s. An anagram uses the same letters, the same number of times, in any order.

Loading videos…

DSA Animator › DSA Revision › Strings › Valid Anagram

Key moments in the Valid Anagram video

0:04Problem0:13Example0:25Brute force0:33Key idea0:46Dry run1:11Code1:31Takeaway

What you will learn

Remember: anagram means equal letter counts. One array of 26 counts: add for s, subtract for t. The video solves Valid Anagram (LeetCode 242, Easy) with the Frequency Count pattern from the Strings topic, and you can replay every step in the interactive Valid Anagram animation.

Valid Anagram video transcript

Problem

You get two strings, s and t. Return true if t is an anagram of s. An anagram uses the same letters, the same number of times, in any order.

Example

anagram and nagaram both have three a, and one each of n, g, r and m. So the answer is true. But rat and car differ, with t in one and c in the other, so that answer is false.

Brute force

The simplest approach sorts both strings and compares them. It works, but sorting takes O of n log n. We can do it in O of n.

Key idea

Count how many times each letter appears. Add 1 for every letter of s. Subtract 1 for every letter of t. If every count ends at 0, the strings are anagrams. And if the lengths differ, return false right away.

Dry run

First, count s. a appears three times, and n, g, r and m once each. Now read t. n arrives, so the count of n drops to 0. a arrives, so a drops to 2. g arrives, so g drops to 0. Another a, so a drops to 1. r arrives, so r drops to 0 as well. Another a, and a reaches 0. Finally m, and m reaches 0. Every count is 0, so the answer is true.

Code

In code, check the lengths first. Then create a count array of size 26. In one loop, add 1 for the letter of s, and subtract 1 for the letter of t. Finally, if any count is not 0, return false, otherwise return true. Time is O of n, and space is O of 1, because the array always has 26 slots.

Takeaway

Remember: anagram means equal letter counts. One array of 26 counts: add for s, subtract for t.

More Strings revision videos

← All 185 DSA revision videos