Two-Heat Results Board

Easytwo pointersAlso known as Merge Sorted Array

A swimming gala runs the 50 m race in two heats. The results board already shows heat 1, fastest time first, and below it there are exactly enough blank rows (shown as 0) for every swimmer in heat 2.

Heat 2's times arrive on a separate sheet, also sorted fastest first. The board has no spare rows for scratch work, so you have to slot heat 2 into the board itself and end up with one combined ranking.

Your task

Write mergeHeats(board, filled, heat2). The first filled entries of board are heat 1's times in non-decreasing order. The remaining heat2.length entries are 0 placeholders. heat2 is also sorted in non-decreasing order.

Change board in place so it holds all the times sorted in non-decreasing order. Return nothing. Do not build a new list and copy it back: use only O(1) extra space.

mergeHeats(board: int[], filled: int, heat2: int[]) → void (changes board in place)

Examples

Example 1
Input
board = [52, 58, 71, 0, 0]
filled = 3
heat2 = [55, 64]
Output
[52, 55, 58, 64, 71]
Why

Heat 1 is 52, 58, 71 and heat 2 is 55, 64. Together, fastest first: 52, 55, 58, 64, 71. The two blank rows are gone.

Example 2
Input
board = [40, 0, 0, 0]
filled = 1
heat2 = [33, 47, 61]
Output
[33, 40, 47, 61]
Why

Heat 2's 33 beats everyone, so it must end up in row 0, where heat 1's 40 currently sits. Writing from the front would destroy the 40 before it is moved.

Constraints

  • 0 ≤ filled, heat2.length ≤ 1,000
  • board.length = filled + heat2.length
  • 1 ≤ every real time ≤ 1,000,000 (hundredths of a second)
Start with brute force

Copy heat 2 into the blank rows, then sort the whole board. Or merge into a fresh list and copy it back.

The first costs O((m + n) log(m + n)) and throws away the fact that both heats were already sorted. The second runs in linear time but needs a second board, which the task rules out. The backward merge gets linear time and no extra list.

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