Two Parcels, Exact Load
Easy · Arrays & Hashing · about 15 min
A courier van has one small slot left that takes exactly load kilograms. The parcels waiting at the depot weigh weights (in the order they arrived). Find two different parcels whose weights add up to exactly load and return their positions [i, j] with i < j.
If several pairs work, return the one with the smallest j; if there is still a tie, the one with the smallest i. If no pair works, return [].
weightshas 0 to 100,000 whole numbers, in no particular order (test data can include zero or negative numbers).- One parcel cannot be used twice.
Examples:
parcel_pair_for_slot([5, 12, 7, 3, 9], 12) → [0, 2] (5 + 7; the pair 3 + 9 ends later)
parcel_pair_for_slot([1, 6, 4, 9], 10) → [1, 2] (6 + 4 ends at position 2, before 1 + 9 ends at position 3)
Hints
- If the current parcel weighs v, what weight would complete the load?
- Remember every weight you have passed, and where you first saw it.
- Look for the partner before you store the current parcel, so a parcel never pairs with itself.
Learn the pattern first: the Arrays & Hashing lesson.
More Arrays & Hashing problems
- First Badge Scanned Twice (Easy)
- Spell It With Tiles (Easy)
- First One-of-a-Kind Character (Easy)
- Group Words With the Same Letters (Medium)
- Trending Hashtags (Medium)
- Longest Streak of Floors (Medium)
- Everyone Else's Product (Medium)
- First Free Ticket Number (Hard)
- Most Lamp Posts in One Line (Hard)