2026-08-25 15:00:56 -04:00
|
|
|
---
|
|
|
|
|
title: '567. Permutation in String'
|
|
|
|
|
description: Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise
|
|
|
|
|
sidebar:
|
|
|
|
|
label: 'Permutation in String'
|
|
|
|
|
badge: 'Medium'
|
|
|
|
|
---
|
|
|
|
|
|
2026-09-21 17:16:10 -04:00
|
|
|
<Badge variant="accent">Hash Table</Badge>
|
2026-08-25 15:00:56 -04:00
|
|
|
|
|
|
|
|
### Example 1:
|
|
|
|
|
- Input: `s1 = "ab", s2 = "eidbaooo"`
|
|
|
|
|
- Output: `true`
|
|
|
|
|
- Explanation: `s2` contains one permutation of `s1` ("ba").
|
|
|
|
|
|
|
|
|
|
### Example 2:
|
|
|
|
|
- Input: `s1 = "ab", s2 = "eidboaoo"`
|
|
|
|
|
- Output: `false`
|
|
|
|
|
|
|
|
|
|
### Constraints:
|
|
|
|
|
|
|
|
|
|
- `1 <= s1.length, s2.length <= 10^4`
|
|
|
|
|
- `s1` and `s2` consist of lowercase English letters.
|
|
|
|
|
|
2026-09-01 14:21:54 -04:00
|
|
|
## Approach
|
|
|
|
|
|
|
|
|
|
```mermaid
|
|
|
|
|
flowchart TD
|
|
|
|
|
S(["checkInclusion(s1, s2)"]) --> G{"k = len(s1) > len(s2)?"}
|
|
|
|
|
G -- yes --> X(["return False"])
|
|
|
|
|
G -- no --> I["need = Counter(s1), window = Counter()"]
|
|
|
|
|
I --> L{"more (right, c) in s2?"}
|
|
|
|
|
L -- no --> E(["return False"])
|
|
|
|
|
L -- yes --> A["window[c] += 1"]
|
|
|
|
|
A --> B{"right >= k? — window is now longer than k"}
|
|
|
|
|
B -- yes --> C["drop s2[right - k] from window, deleting the key at 0"]
|
|
|
|
|
B -- no --> Q
|
|
|
|
|
C --> Q{"window == need?"}
|
|
|
|
|
Q -- yes --> R(["return True"])
|
|
|
|
|
Q -- no --> L
|
|
|
|
|
```
|
|
|
|
|
|
2026-08-25 15:00:56 -04:00
|
|
|
## Solution
|
|
|
|
|
|
|
|
|
|
```py
|
|
|
|
|
from collections import Counter
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class Solution:
|
|
|
|
|
def checkInclusion(self, s1: str, s2: str) -> bool:
|
|
|
|
|
k = len(s1)
|
|
|
|
|
if k > len(s2):
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
need = Counter(s1)
|
|
|
|
|
window = Counter()
|
|
|
|
|
|
|
|
|
|
for right, c in enumerate(s2):
|
|
|
|
|
window[c] += 1
|
|
|
|
|
if right >= k:
|
|
|
|
|
left_char = s2[right - k]
|
|
|
|
|
window[left_char] -= 1
|
|
|
|
|
if window[left_char] == 0:
|
|
|
|
|
del window[left_char]
|
|
|
|
|
if window == need:
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
return False
|
|
|
|
|
```
|
2026-09-01 14:21:54 -04:00
|
|
|
|
|
|
|
|
## Explanation
|
|
|
|
|
|
|
|
|
|
<YouTube id="UbyhOgBN834" title="Permutation in String - Leetcode 567 - Python" />
|