Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Check if a string contains a permutation of a pattern

Determine if any permutation of a given pattern exists as a substring in the input string using a frequency map and sliding window.

Python practice15 minStrings – Sliding Window & FrequencyIntermediateLast updated March 25, 2026

Problem statement

Given a string s and a pattern p, return True if s contains any permutation of p (i.e., any substring of s of length len(p) that is an anagram of p). Otherwise return False. Use frequency counts and a sliding window of size len(p) to check each candidate substring in O(n) time.

Task

Implement a window of fixed size (pattern length) and compare character frequencies efficiently to detect any permutation match.

Examples

Example

Input

s = 'oidbcaf', pattern = 'abc'

Output

True

The substring 'bca' (positions 3..5) is a permutation of 'abc'.

Input format

A function call contains_permutation(s, pattern) where s and pattern are strings.

Output format

A boolean (True/False) indicating whether any permutation of pattern exists in s.

Constraints

0 <= len(s), len(pattern) <= 10^5. Aim for O(n) time and O(min(n, alphabet)) extra space. If pattern is longer than s return False.

Samples

Sample 1

Input

s = 'aaacb', pattern = 'abc'

Output

True

Substring 'acb' is a permutation of 'abc'.