Postcode Stretch on the Van

Mediumbinary searchAlso known as Find First and Last Position of Element in Sorted Array

A delivery van is loaded so the parcels sit on one long rack, sorted by postcode. Many parcels share a postcode, so they form a stretch of neighbours on the rack.

When the driver turns into a new postcode area, the tablet should light up exactly that stretch: the first and the last parcel for that postcode. If no parcel is for this area, it lights nothing.

Your task

Write findStretch(postcodes, code). postcodes is sorted in non-decreasing order. Return [first, last]: the smallest and largest index holding code. If code is not present (or the list is empty), return [-1, -1].

Aim for O(log n) even when one postcode fills most of the rack.

findStretch(postcodes: int[], code: int) → int[]

Examples

Example 1
Input
postcodes = [2040, 2040, 3115, 3115, 3115, 3120, 4500]
code = 3115
Output
[2, 4]
Why

Postcode 3115 fills indexes 2, 3 and 4. Index 1 is still 2040 and index 5 is already 3120, so the stretch is [2, 4].

Example 2
Input
postcodes = [2040, 2040, 3115, 3115, 3115, 3120, 4500]
code = 3200
Output
[-1, -1]
Why

3200 would sit between 3120 and 4500, but no parcel has it, so nothing lights up.

Constraints

  • 0 ≤ postcodes.length ≤ 100,000
  • 1000 ≤ postcodes[i], code ≤ 99,999
  • postcodes is sorted in non-decreasing order.
Start with brute force

Scan the rack and remember the first and last index where the postcode matches. Or binary search for any match and then walk left and right to the edges of the stretch.

Both are O(n) in the worst case. If 99,000 of 100,000 parcels share the postcode, the walk outward visits nearly all of them. Two boundary searches need about 34 looks in total, no matter how long the stretch is.

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