Skip to content
LEETFLIX

Find the Power of K-Size Subarrays II

Solve on LeetCode

Medium · sliding window solution for Find the Power of K-Size Subarrays II. Python, Go, and a step-by-step animation.

01

Problem

Read the prompt, flip through the examples, then steal the idea.

LeetCode 3255. Find the Power of K-Size Subarrays II. The copyrighted prompt is on LeetCode. This page is a working sliding window solution for this problem: editable input, Python, Go, and a step-by-step animation.

Constraints

  • —Player inputs are capped so the animation stays readable.
  • —Match LeetCode's own constraints when you submit there.

Examples

Input

s =
abcabcbb

Output

3

The longest unique window is abc (length 3).

02

Solution

Python and Go. The walkthrough below runs this same code.

Approach 1Optimal▶ Animated

Find the Power of K-Size Subarrays II — sliding window

Grow right, shrink left the moment the window breaks its invariant. Built for LeetCode 3255. Find the Power of K-Size Subarrays II.

The window [left, right] is the longest suffix ending at right that still obeys the rule (here: all unique). Last-seen indices tell you exactly how far to jump left.

Algorithm

  1. Walk right across the string.
  2. If s[right] was already inside the window, jump left past its last index.
  3. Record the last-seen index and update the best length.
Time
O(n)
Space
O(σ)
Solution.py
class Solution:    def findThePowerOfKSizeSubarraysIi(self, s: str) -> int:        last: dict[str, int] = {}        left = 0        best = 0        for right, ch in enumerate(s):            if ch in last and last[ch] >= left:                left = last[ch] + 1            last[ch] = right            best = max(best, right - left + 1)        return best
Watch this run

03

Interactive walkthrough

Playing “Find the Power of K-Size Subarrays II — sliding window”. Edit the input, hit Run, then scrub.

Approach: Find the Power of K-Size Subarrays II — sliding window

Loading animation…