Postcode Stretch on the Van

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

A delivery van's parcels sit on one long rack, sorted by postcode. Parcels sharing a postcode form a stretch of neighbours.

When the driver enters a postcode area, the tablet lights up that stretch by showing the first and last parcel for the postcode, or nothing if there are none.

Your task

Write findStretch(postcodes, code). postcodes is sorted in non-decreasing order. Return [first, last], where first is the smallest index holding code and last is the largest. 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, while index 1 holds 2040 and index 5 holds 3120.

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

The postcode 3200 would sit between 3120 and 4500, but no parcel has it.

Constraints

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

One approach is to scan the rack for the first and last match. Another is to binary search for any match and then walk left and right to the edges.

Both are O(n) in the worst case: if 99,000 of 100,000 parcels share the postcode, the walk visits nearly all of them. Two boundary searches need about 34 comparisons in total, however 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