⚡Flashcard Drill➔
NeetCode #232LC-567MediumSliding WindowNC 150NC 250
← Back to All Problems

#232 · #567 · Permutation in String(字符串的排列)

📌 Problem Statement & Constraints

Given two strings s1 and s2, return true if s2 contains a permutation of s1 as a substring. Constraints: 1 <= s1.length, s2.length <= 10^4, lowercase letters.

💡 Core Algorithmic Approaches

  1. A permutation of s1 must have exactly len(s1) characters, so only fixed-length windows of that size matter.
  2. Compare the character counts of the window with those of s1.
  3. Slide the window one character at a time, adding the entering character and removing the leaving one.
  4. Remember to delete zero-count keys from the window counter, otherwise the equality test fails spuriously.

💻 Benchmark Python3 Implementation

class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        from collections import Counter
        k = len(s1)
        if len(s2) < k:
            return False
        need = Counter(s1)
        window = Counter(s2[:k])
        if window == need:
            return True
        for i in range(k, len(s2)):
            window[s2[i]] += 1
            left = s2[i - k]
            window[left] -= 1
            if window[left] == 0:
                del window[left]           # keep the counters comparable
            if window == need:
                return True
        return False

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n) with a constant factor of 26 for each counter comparison.
💾 Space Complexity
O(1): the counters hold at most 26 entries.

⚠️ Interview Pitfalls & Follow-ups

  • Not deleting zero-count keys: Counter({'a': 0}) != Counter({}), so the comparison would fail. This is the most common bug.
  • Checking the initial window only inside the loop: the first window must be tested before the slide loop starts.
  • Using sorted(window.items()): needlessly expensive; Counter supports direct equality.
  • Skipping the length guard: slicing s2[:k] when k > len(s2) yields a short window, and the comparison would silently fail -- the explicit guard documents the intent.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Sliding Window Problems

中文速览与面试要点

字符串的排列

给你两个字符串 s1 和 s2,写一个函数来判断 s2 是否包含 s1 的排列。如果是,返回 true;否则,返回 false。换句话说,s1 的排列之一是 s2 的 子串 。约束:1 ≤ s1.length, s2.length ≤ 10^4;s1 和 s2 仅包含小写字母。

核心要点

  • 定长滑动窗口(标准解) :窗口长度固定为 len(s1) 。用两个计数表分别记录 s1 的字符需求与当前窗口的字符构成。
  • 滑动更新 :窗口右移时加入新字符、移除最左字符;某字符计数降为 0 时 必须从字典中删除 ,否则字典相等比较会失败。
  • 为什么定长 :排列与原串长度相同,因此只需检查所有长度等于 len(s1) 的窗口。
  • 提前剪枝 :若 len(s2) &lt; len(s1) 直接返回 False。

常见陷阱

  • 不清理零计数键 : Counter("a": 0) 与 Counter() 不相等,会导致字典比较失败。必须显式 del 。
  • 窗口右移时忘记移除左端字符 :窗口会无限增长,结果错误。
  • 用排序后的子串比较 :每次是 O(k log k),整体 O(n · k log k),在大输入下超时。
  • 误以为要找「完全相同的子串」 :题目要求的是 排列 (字符构成相同、顺序任意)。

参考实现

from collections import Counter

class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        k = len(s1)
        if len(s2) < k:
            return False
        need = Counter(s1)
        window = Counter()
        for i, c in enumerate(s2):
            window[c] += 1
            if i >= k:                      # 移除滑出窗口的字符
                out = s2[i - k]
                window[out] -= 1
                if window[out] == 0:
                    del window[out]         # 关键:清理零计数键
            if window == need:
                return True
        return False