Market Street Errand

Hardsliding windowAlso known as Minimum Window Substring

On Saturdays a long street turns into a market. The stalls stand in one row, and each sells a single kind of thing, written as a letter: b for bread, h for honey, e for eggs. Several stalls can sell the same thing. The street, read from one end, is a string like "ebxhbqe".

Your shopping list, wanted, is also written as letters, and each stall sells you one item. Your bags are heavy, so you want to walk the shortest unbroken section of the street where you can buy everything on the list.

Your task

Write shortestErrand(street, wanted). Return the shortest substring of street that contains every character of wanted, including repeats: if wanted has two h's, the substring needs at least two h's. Extra stalls inside the section are fine.

If several substrings tie for shortest, return the one that starts first (leftmost). If no section works, return the empty string "". Letters are case-sensitive.

shortestErrand(street: string, wanted: string) → string

Examples

Example 1
Input
street = "ebxhbqe"
wanted = "hbe"
Output
"ebxh"
Why

The section ebxh (stalls 0 to 3) has e, b and h, length 4. The section hbqe (stalls 3 to 6) also has all three, but it is also length 4 and starts later. Nothing shorter works: every 3-stall section is missing at least one item.

Example 2
Input
street = "hbhxxeh"
wanted = "hhe"
Output
"hxxeh"
Why

The list needs two h's and an e. hbhxxe (length 6) works, but hxxeh (stalls 2 to 6, length 5) is shorter. Counting only the kinds of item, and not how many, would wrongly accept eh.

Constraints

  • 0 ≤ street.length ≤ 10,000
  • 1 ≤ wanted.length ≤ 1,000
  • street and wanted contain letters a-z and A-Z only.
Start with brute force

Try every start and every end, count the letters in that section, and check them against the list. Or, slightly better, try each length from 1 upward and stop at the first length where some section works.

There are about 50 million sections in a 10,000-stall street, and each check costs more work. Even the smarter version recounts overlapping sections over and over, when a section and its neighbour differ by just one stall.

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