DSA AnimatorREVISION VIDEOS
← Back to problems
New

Permutation in String — LeetCode 567 video explanation

Given two strings, s 1 and s 2, return true if s 2 contains some permutation of s 1 as a substring.

Loading videos…

DSA Animator › DSA Revision › Strings › Permutation in String

Key moments in the Permutation in String video

0:04Problem0:12Example0:22Brute force0:30Key idea0:42Dry run0:56Code1:11Takeaway

What you will learn

Remember: permutation means equal letter counts. A fixed window updates two counts per step. The video solves Permutation in String (LeetCode 567, Medium) with the Fixed Sliding Window pattern from the Strings topic, and you can replay every step in the interactive Permutation in String animation.

Permutation in String video transcript

Problem

Given two strings, s 1 and s 2, return true if s 2 contains some permutation of s 1 as a substring.

Example

For s 1 equal to a b, and s 2 equal to e i d b a o o o, the answer is true. The substring b a, at index 3, is a permutation of a b.

Brute force

Generating every permutation of s 1 is factorial time. Sorting every window of s 2 and comparing is also slow.

Key idea

A permutation has exactly the same letter counts. So slide a window of length s 1 across s 2, and compare letter counts. Each slide only changes two counts: one letter in, one letter out.

Dry run

The counts of s 1 are a 1 and b 1. Window e i: no match. Window i d: no match. Window d b: no match. Window b a: the counts are a 1 and b 1, which match. So the answer is true.

Code

In code, count the letters of s 1, and of the first window. Slide right: add the new letter and remove the one that left. Return true as soon as the two count arrays are equal. Each comparison is 26 checks, so it's O of n time and O of 1 space.

Takeaway

Remember: permutation means equal letter counts. A fixed window updates two counts per step.

More Strings revision videos

← All 185 DSA revision videos