Market Street Errand

Hardsliding windowAlso known as Minimum Window Substring

On Saturdays a long street becomes a market. Stalls stand in one row, each selling one kind of thing, written as a letter: b for bread, h for honey, e for eggs. Several stalls can sell the same thing. Read from one end, the street is a string like "ebxhbqe".

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

Your task

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

On a tie for shortest, return the leftmost. If no section works, return "". Letters are case-sensitive.

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

Examples

Example 1
Input
street = "ebxhbqe"
wanted = "hbe"
Output
"ebxh"
Whyebxh (stalls 0 to 3) has e, b and h, length 4. hbqe (stalls 3 to 6) also has all three at length 4, but starts later. Every 3-stall section misses 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 kinds, 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 end, count the letters, and check them against the list. Or try each length from 1 upward and stop at the first that works.

A 10,000-stall street has about 50 million sections, each costly to check. Even the smarter version recounts overlapping sections, though neighbours 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