Add a zip code to sorted zip code ranges by extending a neighbour or merging two
Problem
A delivery service stores the zip codes it covers as a sorted list of ranges. Write addZipCode(ranges, zip) that returns the list after adding one more zip code.
- A zip code is an integer from
0to99999. rangesis an array of pairs[start, end]withstart <= end. Both ends are included, so[12340, 12355]covers 16 zip codes.- The ranges are sorted by
startand are separate: at least one uncovered zip code lies between two neighbours. So[1, 3], [4, 6]is not a valid list, because it should be[1, 6].
Add zip with these rules, in this order:
- If a range already contains
zip, nothing changes. - If
zipis one more than the end of a range and one less than the start of the next, the two ranges merge into one. - If
zipis one more than the end of a range, that range grows by one at the end. - If
zipis one less than the start of a range, that range grows by one at the start. - Otherwise, insert
[zip, zip]in sorted position.
Return a new array of new pairs. Never change ranges or its pairs, even when nothing changes.
Validate the input:
- Throw a
TypeErrorifzipis not an integer, or ifrangesis not an array of two-integer arrays. - Throw a
RangeErrorifzipor any range end is outside0to99999, a range hasstart > end, or the ranges are not sorted and separate.
addZipCode([[12340, 12355], [12400, 12450]], 12345); // [[12340, 12355], [12400, 12450]]
addZipCode([[12347, 12355], [12400, 12450]], 12346); // [[12346, 12355], [12400, 12450]]
addZipCode([[11230, 11234], [11236, 11238]], 11235); // [[11230, 11238]]
addZipCode([[100, 200]], 500); // [[100, 200], [500, 500]]
addZipCode([], 90210); // [[90210, 90210]]Ref. UR-1539 · © UIRound · uiround.com/questions/add-a-zip-code-to-sorted-zip-code-ranges-by-extending-a-neighbour-or-merging-two
Unlock this question
Its tests and the tested solution are part of Pro.
- 2
- code listings
- 6
- edge cases
- 5
- follow-up questions
What's inside
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Private, and saved in this browser as you type. All your notes are on My lists.