Adjacent Spice Jars

Mediumsliding windowAlso known as Permutation in String

A busy restaurant kitchen has one long shelf of spice jars. Each jar is labelled with one letter: c for cumin, p for paprika, s for salt, and so on. The shelf, read left to right, is a string like "sppcsx".

A recipe card lists the jars it needs, for example "cps". The chef wants to grab everything with one sweep of the arm: a block of jars standing side by side that holds exactly the recipe's jars, in any order, with nothing extra. Is there such a block on the shelf?

Your task

Write hasSpiceBlock(shelf, recipe). Return true if some run of recipe.length consecutive characters in shelf contains 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
Why

The first two blocks, spp and ppc, each have two p's. The block at positions 2 to 4, pcs, has one c, one p and one s: exactly the recipe, in a different order. Return 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 has two a's, even though the shelf has two a's in total. They are just 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, take the next m jars, sort them, and compare with the sorted recipe.

Sorting each block costs about m log m. With a 10,000-jar shelf and a 1,000-letter recipe that is roughly 9,000 blocks × 10,000 steps: around 90 million operations. All that recounting is wasted, because 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