Sliding Window Fixed-size window

178. Permutation in String

Medium 147 DSA Sheet

You are given two strings, pattern and text. Return true if some substring of text is a rearrangement of pattern, and false otherwise.

A rearrangement of pattern holds exactly the same letters as pattern, each one the same number of times, in any order. pattern itself counts as one of its rearrangements. A substring is a block of letters that sit next to each other in text.

Example 1

Input: pattern = "stop", text = "despotic"

Output: true

Explanation: The block "spot", from index 2 to index 5, holds one each of s, t, o and p, the same letters as stop in a different order.

Example 2

Input: pattern = "gum", text = "magnum"

Output: false

Explanation: Every letter of gum appears in magnum, but never all three side by side. The blocks of three letters are "mag", "agn", "gnu" and "num", and each one holds a letter that gum lacks.

Example 3

Input: pattern = "street", text = "trees"

Output: false

Explanation: text has five letters and pattern has six, so no block of text is long enough. Even the whole of text holds only one t, where street has two.

Check your understanding

Work out the answer for this input before you write any code.

pattern = "aab", text = "abbab"

Constraints

  • 1 ≤ pattern.length, text.length ≤ 105
  • pattern and text hold lowercase English letters only.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.