Adjacent Spice Jars

Mediumsliding windowAlso known as Permutation in String

A restaurant kitchen has one long shelf of spice jars, each labelled with a letter (c for cumin, p for paprika). Read left to right, the shelf is a string like "sppcsx".

A recipe card lists the jars it needs, like "cps". Can the chef grab them in one sweep, meaning a block of side-by-side jars that holds exactly the recipe's jars, in any order, with nothing extra?

Your task

Write hasSpiceBlock(shelf, recipe). Return true if some run of recipe.length consecutive characters in shelf has exactly the same letters as recipe, each the same number of times, in any order. Otherwise return false.

If recipe is longer than shelf, return false.

hasSpiceBlock(shelf: string, recipe: string) → bool

Examples

Example 1
Input
shelf = "sppcsx"
recipe = "cps"
Output
true
Whyspp and ppc each have two p's. The block at positions 2 to 4, pcs, has one c, one p and one s, which is the recipe in a different order, so the answer is true.
Example 2
Input
shelf = "paspca"
recipe = "aap"
Output
false
Why

The recipe needs two a's and one p. The 3-jar blocks are pas, asp, spc, pca. None of them has two a's, because the shelf's two a's are too far apart.

Constraints

  • 1 ≤ recipe.length ≤ 1,000
  • 0 ≤ shelf.length ≤ 10,000
  • shelf and recipe contain lowercase letters a-z only.
Start with brute force

For every starting position, sort the next m jars and compare with the sorted recipe.

Each sort costs about m log m. A 10,000-jar shelf and a 1,000-letter recipe give roughly 9,000 blocks × 10,000 steps, which is around 90 million operations, even though each block differs from the previous one by just two jars.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code