KatInterview

Order Each Neighboring Couple in a List, Skipping a Lone Tail

Arrays & HashingAuto-graded · 20 test cases
EasyAuto-gradedArrays & Hashingarraystwo-pointerssimulation

Last updated

Reorder the two values inside every consecutive couple of a list so the smaller comes first, keeping couples in place and leaving an unpaired final value alone.

You are given a list of integers. Group its positions into consecutive couples starting at the front: positions (0, 1), then (2, 3), then (4, 5), and so on. Inside each couple, arrange the two values so that the smaller one comes first and the larger one second.

Couples are fixed blocks. A couple never changes its position relative to the others, and a value never moves into a different couple. The list as a whole is therefore usually not sorted afterward.

If the list has an odd number of elements, the last element has no partner and must remain exactly where it is, even if it is smaller than the values before it.

Task

Implement a function that receives the list values and returns a list of the same length in which every couple has been ordered as described.

Rules

  • For every even index i such that i + 1 < len(values), the result has min(values[i], values[i + 1]) at index i and max(values[i], values[i + 1]) at index i + 1.
  • If len(values) is odd, the last element of the result equals the last element of values.
  • A couple of equal numbers stays as it is.
  • The returned list must have the same length as the input. You may return a new list or modify the input in place and return it.

Constraints

  • 1 <= len(values) <= 10^5
  • -10^9 <= values[i] <= 10^9

Examples

Example 1

Input: order_couples([5, 4, 2, 3, 7])

Output: [4, 5, 2, 3, 7]

Example 2

Input: order_couples([9, 1, 8, 2])

Output: [1, 9, 2, 8]

Example 3

Input: order_couples([6])

Output: [6]

Hints

Hint 1

Pairs are independent of each other, so a global sort is unnecessary. Only two neighboring elements ever need to be compared.

Hint 2

Walk through the list with a step of 2, starting at index 0. At each stop, swap the element with its right neighbor only if the left one is larger.

Hint 3

Choose the loop bound so that index i + 1 always exists. Stopping the range at len(values) - 1 automatically skips the unpaired last element of an odd-length list.