All problems
0187HardArrayHash TableSliding WindowCounting

Stretches Using Exactly K Spools

Tracked in this browser only
Write code

Trains the technique from

LeetCode 992Subarrays with K Different Integers

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A loom records which yarn spool it drew from for each stitch it makes, in the order the stitches were made, as the array stitches. Spools are labelled from 1 up to the number of stitches on the strip.

A stretch is a run of neighbouring stitches with nothing skipped in the middle. Count the stretches that draw on exactly k different spools.

Two stretches count separately whenever they start or end at different stitches, even if the spools they use happen to be the same. Return that count.

Examples

Example 1

Input
stitches = [4, 4, 2, 4], k = 2
Output
5

The qualifying stretches run over stitches 1-3, 1-4, 2-3, 2-4 and 3-4; every other stretch touches just one spool.

Example 2

Input
stitches = [3, 3, 3], k = 1
Output
6

One spool made the whole strip, so all six stretches qualify.

Example 3

Input
stitches = [2, 2], k = 2
Output
0

Only one spool appears anywhere on the strip, so no stretch can reach two.

Constraints

  • 1 <= stitches.length <= 2 * 10^4
  • 1 <= stitches[i] <= stitches.length
  • 1 <= k <= stitches.length

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def stretches_with_k_spools(stitches: list[int], k: int) -> int:
Java
public int stretchesWithKSpools(int[] stitches, int k)
September 7
Apply