Add a zip code to sorted zip code ranges by extending a neighbour or merging two

mediumAbout 20 minutesUpdated CodingProAsked atMozillaintervalsbinary-searcharraysimmutability
Not solved

Share this question

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 0 to 99999.
  • ranges is an array of pairs [start, end] with start <= end. Both ends are included, so [12340, 12355] covers 16 zip codes.
  • The ranges are sorted by start and 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:

  1. If a range already contains zip, nothing changes.
  2. If zip is one more than the end of a range and one less than the start of the next, the two ranges merge into one.
  3. If zip is one more than the end of a range, that range grows by one at the end.
  4. If zip is one less than the start of a range, that range grows by one at the start.
  5. 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 TypeError if zip is not an integer, or if ranges is not an array of two-integer arrays.
  • Throw a RangeError if zip or any range end is outside 0 to 99999, a range has start > 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

Private, and saved in this browser as you type. All your notes are on My lists.

Every question and answer7 days, one payment