Choose Extreme Shipment Weights
Context
A freight hub is preparing a special loading list. From the recorded weights of incoming shipments, it must keep the lightest k shipments and the heaviest k shipments. The list is organized by weight, duplicate weights remain separate, and a shipment position that belongs to both groups is included only once.
Problem
Given an integer array shipments and an integer k, return the shipment weights occupying the first k and last k positions after sorting shipments in nondecreasing order. Preserve every selected occurrence, including duplicate values. If the two selected ranges overlap, include each array position only once. When k is zero or shipments is empty, return an empty array. The returned array must remain in nondecreasing order.
Examples
k = 2shipments = [12, 5, 19, 7, 5, 14][5, 5, 14, 19]k = 2shipments = [8, 3, 8, 3, 5][3, 3, 8, 8]k = 0shipments = [4, 4, 4, 9][]Constraints
0 <= len(shipments) <= 100000-1000000000 <= shipments[i] <= 1000000000 for every i0 <= k <= len(shipments)- Types:
shipmentsis int[],kis int; result is int[]
Function signature
def select_extreme_shipments(shipments: list[int], k: int) -> list[int]
shipmentslist[int]- Weights of shipments recorded at the hub.
kint- Number of positions to select from each end of the sorted shipment list.
- returns list[int]
- The sorted shipment weights from the first k and last k sorted positions, with overlapping positions included once and duplicate occurrences preserved.
Adapted from MBPP problem task_219 (CC BY 4.0). Rewritten, extended and verified by Iksha.
Notes
- Selection is based on sorted positions, not distinct weight values.
- If the low-end and high-end ranges overlap, their union is returned without duplicating an overlapping position.