MEDIUM NC#18 Sliding Window

567. Permutation in String

๐Ÿ“– Problem

Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise. In other words, return true if one of s1's permutations is the substring of s2.

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing
  • โ€ขString/array indexing
  • โ€ขSet/Map frequency counting
  • โ€ขPointer movement invariants

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation
  • โ€ขApply Sliding Window reasoning pattern

๐Ÿ’ก Approach

  • โ†’ Permutation means same characters with same counts
  • โ†’ Use sliding window of size s1.length on s2
  • โ†’ Track character counts in current window
  • โ†’ Expand right and shrink left while maintaining window size
  • โ†’ Optimize by tracking count of matching characters
  • โ†’ Time: O(len(s1) + len(s2)), Space: O(26) constant

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขPermutation means same characters with same counts
  • โ€ขUse sliding window of size s1.length on s2
  • โ€ขTrack character counts in current window

Common Pitfalls

  • โ€ขExpand right and shrink left while maintaining window size
  • โ€ขOptimize by tracking count of matching characters
  • โ€ขTime: O(len(s1) + len(s2)), Space: O(26) constant

๐Ÿงช Test Cases

Hidden tests on submit: 2

Test Case 1
Not run
Input:
checkInclusion('ab', 'eidbaooo');
Expected:
true
Test Case 2
Not run
Input:
checkInclusion('ab', 'eidboaoo');
Expected:
false
Test Case 3
Not run
Input:
checkInclusion('adc', 'dcda');
Expected:
true

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit