429. Locate Parcel Weight Group
Asked in
Locate Parcel Weight Group

A shipping center places parcels in a row from the lightest to the heaviest.

Several parcels may have the same recorded weight. Find the first and last positions in the row containing parcels with a requested weight.

Class

ParcelRow

Method

locateWeightGroup

List<Integer> locateWeightGroup( List<Integer> parcelWeights, int wantedWeight )

Parameters

  • parcelWeights: The parcel weights in their row order.
  • wantedWeight: The parcel weight to locate.

Returns

Return a list containing the first and last positions where wantedWeight appears.

Positions are indexed from 0, and both returned positions are inclusive.

If no parcel has the requested weight, return List.of(-1, -1).

Row Rules

  • parcelWeights is sorted in non-decreasing order.
  • Parcels with the same weight appear consecutively.
  • If exactly one parcel has the requested weight, return its position twice.
  • The returned first position must not be greater than the returned last position.
  • The method must run in O(log n) time, where n is the number of parcels.

Constraints

  • 0 ≤ parcelWeights.size() ≤ 100,000
  • 1 ≤ parcelWeights.get(i) ≤ 1,000,000,000
  • 1 ≤ wantedWeight ≤ 1,000,000,000
  • parcelWeights is sorted in non-decreasing order.
  • No parameter value is null.

Example 1

locateWeightGroup( parcelWeights = List.of(150, 220, 220, 220, 480, 650), wantedWeight = 220 )

Output: List.of(1, 3)

Parcels weighing 220 grams occupy positions 1 through 3 in the row.

Example 2

locateWeightGroup( parcelWeights = List.of(90, 140, 140, 275, 430), wantedWeight = 200 )

Output: List.of(-1, -1)

No parcel in the row weighs 200 grams.

Example 3

locateWeightGroup( parcelWeights = List.of(75, 100, 160, 240), wantedWeight = 160 )

Output: List.of(2, 2)

Only the parcel at position 2 has the requested weight.

Example 4

locateWeightGroup( parcelWeights = List.of(), wantedWeight = 500 )

Output: List.of(-1, -1)

The row is empty, so the requested weight cannot be found.



Please use Laptop/Desktop or any other large screen to add/edit code.