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 shows heat 1, fastest first, followed by one blank row (0) per heat 2 swimmer.

Heat 2's times arrive on a sheet, also sorted fastest first. With no spare rows for scratch work, you must slot heat 2 into the board itself to get 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 ignores that both heats are sorted. The second is linear but needs a second board, which the task rules out. The backward merge is linear with 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