Market Street Errand
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
street = "ebxhbqe" wanted = "hbe"
"ebxh"
ebxh (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.street = "hbhxxeh" wanted = "hhe"
"hxxeh"
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- Hint 1
In the first example, walk from the start until you have everything, which happens at stall 3 with
ebxh. Could you drop the first stall and still have everything? What does that tell you about where to look next? - Hint 2
Every valid section ends at some stall, and for each end you want the latest start that still covers the list. As the end moves right, that best start never moves left.
- Hint 3
So use a sliding window. Move the right edge one stall at a time. When the window covers the list, pull the left edge in as far as it stays covering, record it, and then pull once more to break it and continue.
- Hint 4
To check "covers the list" in O(1), keep
need(how many of each letter the list still wants) andmissing(how many list items are uncovered). When a stall enters andneed[c] > 0, decreasemissing; decreaseneed[c]either way. Whenmissingis 0, shrink from the left, adding back toneedand increasingmissingwhen it goes above 0. Record a window only if strictly shorter, which keeps the leftmost tie.
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.
How to solve it
Slide a window over the street. The right edge adds stalls until the window covers the list. Then the left edge removes stalls for as long as the window still covers the list, and each removal gives a shorter candidate. Once the window stops covering the list, the right edge grows again.
The bookkeeping uses two values. need[c] is how many more c's the window wants (a negative value means spares), and missing is the total still wanted. The window covers the list exactly when missing is 0.
Trace "ebxhbqe" with list "hbe" (need h 1, b 1, e 1, missing 3):
- Adding e (stall 0) makes missing 2, adding b makes it 1, and adding x leaves it unchanged because x is not wanted (need[x] = -1).
- Adding h (stall 3) makes missing 0, so the best so far is
ebxhwith length 4. Dropping e puts need[e] back to 1 and missing back to 1, so shrinking stops. - Adding b (stall 4) is a spare because need[b] was 0, so missing stays 1, and adding q is also a spare.
- Adding e (stall 6) makes missing 0 with the window
bxhbqe, length 6, which is not better. Dropping the spare b givesxhbqe, length 5, and dropping x giveshbqe, length 4, which ties and is not strictly shorter, so the leftmost answer stays. Dropping h makes missing 1, so shrinking stops.
The answer is ebxh. Each stall is added once and dropped at most once, so the work is linear.
function shortestErrand(street, wanted) {
const need = new Map(); // letter -> how many more the window needs
for (const c of wanted) need.set(c, (need.get(c) || 0) + 1);
let missing = wanted.length;
let left = 0, bestStart = 0, bestLen = Infinity;
for (let right = 0; right < street.length; right++) {
const c = street[right];
if ((need.get(c) || 0) > 0) missing--;
need.set(c, (need.get(c) || 0) - 1);
while (missing === 0) {
if (right - left + 1 < bestLen) { bestStart = left; bestLen = right - left + 1; }
const out = street[left];
need.set(out, need.get(out) + 1);
if (need.get(out) > 0) missing++; // dropped a stall we needed
left++;
}
}
return bestLen === Infinity ? "" : street.slice(bestStart, bestStart + bestLen);
}def shortest_errand(street, wanted):
need = {} # letter -> how many more the window needs
for c in wanted:
need[c] = need.get(c, 0) + 1
missing = len(wanted)
left = best_start = 0
best_len = float('inf')
for right, c in enumerate(street):
if need.get(c, 0) > 0:
missing -= 1
need[c] = need.get(c, 0) - 1
while missing == 0:
if right - left + 1 < best_len:
best_start, best_len = left, right - left + 1
out = street[left]
need[out] += 1
if need[out] > 0:
missing += 1 # dropped a stall we needed
left += 1
if best_len == float('inf'):
return ""
return street[best_start:best_start + best_len]Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.