00:00

Problem Statement

Input/Output Examples

Visual Explanation

The window at index 1 is "ava", which has two a's and no j, so it is rejected. Updating two counts per slide makes every check constant time.

Approaches

Both approaches check every window of length |p|. The first updates counts as it slides; the second sorts each 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; sorting each window costs O(m log m) per position.

Interview Tips and Recommended Approach

  • Allow overlaps. Matches can start one position apart, as in "abab".
  • Recognise the fixed window. Every anagram of p has exactly |p| characters.
  • Optimise the comparison if asked. Track how many of the 26 counts currently match instead of comparing arrays.
  • Return indexes, not substrings, unless the interviewer asks for the text.

Recommended Approach: Sliding Window Counts

Why: it scans the text once with two fixed-size arrays, and the update-two-counts pattern carries over to many other window problems.