PracticeSorting

Choose Extreme Shipment Weights

EasySortingsortingtraversalfiltering Time not estimated Not started

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

Example 1
Input: k = 2shipments = [12, 5, 19, 7, 5, 14]
Output: [5, 5, 14, 19]
Explanation: The sorted weights are [5, 5, 7, 12, 14, 19]. With k = 2, the selected result is [5, 5, 14, 19].
Example 2
Input: k = 2shipments = [8, 3, 8, 3, 5]
Output: [3, 3, 8, 8]
Explanation: The sorted weights are [3, 3, 5, 8, 8]. With k = 2, the selected result is [3, 3, 8, 8].
Example 3
Input: k = 0shipments = [4, 4, 4, 9]
Output: []
Explanation: With k = 0, the executed result is an empty array.

Constraints

  • 0 <= len(shipments) <= 100000
  • -1000000000 <= shipments[i] <= 1000000000 for every i
  • 0 <= k <= len(shipments)
  • Types: shipments is int[], k is int; result is int[]

Function signature

def select_extreme_shipments(shipments: list[int], k: int) -> list[int]
shipments list[int]
Weights of shipments recorded at the hub.
k int
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.
Approved · c004r1-abs_673_v214 execution-verified tests
Code
Saved
Checking environment…Python SandboxLn 1, Col 1