PracticeArrays

Check Shipment Weight Order

EasyArraystraversalstate trackinginvariants Time not estimated Not started

Context

A warehouse loads shipments onto a delivery truck in a planned sequence. The loading supervisor wants to know whether each shipment is no lighter than the one immediately before it, so the weights never decrease along the route. Equal weights are acceptable, and an empty or one-shipment load is considered ordered.

Problem

Implement a function that checks whether the shipment weights are in nondecreasing order from the first loaded shipment to the last. For every neighboring pair, the later weight must be greater than or equal to the earlier weight. If any neighboring pair decreases, the sequence is not ordered. Return true when all adjacent pairs satisfy the rule. Empty and single-element arrays have no violating pair and must return true. Use a single scan with constant extra space; do not sort or rearrange the input.

Examples

Example 1
Input: weights = [12, 18, 18, 25]
Output: True
Explanation: For [12, 18, 18, 25], the executed function returns true, and its final order_ok value is true.
Example 2
Input: weights = [5, 9, 14, 20]
Output: True
Explanation: For [5, 9, 14, 20], the executed function returns true, and its final order_ok value is true.
Example 3
Input: weights = [30, 27, 27, 35]
Output: False
Explanation: For [30, 27, 27, 35], the executed function returns false, and its final order_ok value is false.

Constraints

  • 0 <= len(weights) <= 100000
  • -1000000 <= weights[i] <= 1000000 for every i
  • Types: weights is int[]; result is bool

Function signature

def is_shipment_ordered(weights: list[int]) -> bool
weights list[int]
Shipment weights listed in the order they are loaded onto the delivery truck.
returns bool
True if the shipment weights never decrease from one adjacent shipment to the next; otherwise false.

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

Approved · c011-abs_431_v214 execution-verified tests
Code
Saved
Checking environment…Python SandboxLn 1, Col 1