PracticeSorting

Choose the Earliest Shipments

EasySortingsortingcomparisonboundary handling Time not estimated Not started

Context

A warehouse dispatch team tracks shipments as two-number records: the first number is the scheduled delivery time, and the second identifies the shipment. They need a dispatch list containing at most a requested number of shipments, starting with the earliest deliveries.

Problem

Write a function that receives shipment records and a requested limit. Each record has exactly two integers: delivery time first and shipment identifier second. Order all records by delivery time from smallest to largest, then return the first requested number of complete records. If several records have the same delivery time, keep them in their original input order. Do not remove duplicate records, and return an empty list when the requested limit is zero or there are no shipments.

Examples

Example 1
Input: limit = 3shipments = [[5, 101], [2, 102], [8, 103], [2, 104]]
Output: [[2, 102], [2, 104], [5, 101]]
Explanation: The executed result orders delivery times as 2, 2, and 5, keeps both equal-time records, and returns three complete records: [[2, 102], [2, 104], [5, 101]].
Example 2
Input: limit = 1shipments = [[10, 501], [4, 502], [7, 503]]
Output: [[4, 502]]
Explanation: The executed result returns one complete record with the smallest delivery time: [[4, 502]].
Example 3
Input: limit = 4shipments = [[3, 201], [3, 201], [1, 202], [6, 203]]
Output: [[1, 202], [3, 201], [3, 201], [6, 203]]
Explanation: The executed result keeps both duplicate records and returns all four complete records in nondecreasing delivery-time order: [[1, 202], [3, 201], [3, 201], [6, 203]].

Constraints

  • 0 <= len(shipments) <= 100
  • 2 <= len(shipments[i]) <= 2 for every i
  • 0 <= shipments[i][j] <= 1000000 for every i, j
  • shipments: rectangular
  • 0 <= limit <= len(shipments)
  • Types: shipments is int[][], limit is int; result is int[][]

Function signature

def choose_earliest_shipments(shipments: list[list[int]], limit: int) -> list[list[int]]
shipments list[list[int]]
Shipment records, each containing delivery time followed by shipment identifier.
limit int
Maximum number of shipments to include in the dispatch list.
returns list[list[int]]
The selected complete shipment records, ordered by nondecreasing delivery time and containing no more than limit records.

Adapted from MBPP problem task_753 (CC BY 4.0). Rewritten, extended and verified by Iksha.

Notes

  • The first number in every record is the ranking key.
  • Equal ranking keys retain their input order.
Approved · cb055-abs_153_v114 execution-verified tests
Code
Saved
Checking environment…Python SandboxLn 1, Col 1