00:00

Problem Statement

Input/Output Examples

Visual Explanation

Moving the window one step adds one character on the right and removes one on the left, so the counts can be updated in constant time instead of being recounted.

Approaches

Both approaches compare letter counts. The first updates the counts as the window slides; the second recounts every window.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the length of s and m the length of p. The sliding window does constant work per position; recounting does m work per position.

Interview Tips and Recommended Approach

  • Recognise the fixed window. A permutation has the same length as p, so the window size never changes.
  • Update, do not recount. One increment and one decrement per slide is the whole optimisation.
  • Mention the matches counter. Tracking how many of the 26 letters currently match avoids comparing whole arrays.
  • Know the sibling problem: returning every start index instead of true/false uses the same window.

Recommended Approach: Sliding Window Counts

Why: it scans s once with two fixed-size arrays, which is the expected linear-time answer and the template for many anagram-window problems.