Sort Each Adjacent Pair of an Array, Leaving an Odd Last Element in Place
Capital OneSoftware Engineer · Online AssessmentLast updated
Given an integer array, put each consecutive pair of elements in ascending order while keeping every pair in its original place, and leave the final element untouched when the length is odd. Tests precise reading of a short specification and careful index handling.
Given an array of integers, sort it by pairs. Split the array into consecutive pairs starting from the first element, (nums[0], nums[1]), (nums[2], nums[3]), and so on, and put the two numbers of every pair in ascending order. Pairs never move relative to one another, and no number moves from one pair into another.
If the array has an odd length, the last number has no partner and stays where it is.
Function Signature
def sort_pairs(nums: list[int]) -> list[int]:
Rules
- For every even index
iwithi + 1 < len(nums), the output holds the smaller ofnums[i]andnums[i + 1]at indexiand the larger at indexi + 1. - If
len(nums)is odd, the last element of the output equals the last element ofnums. - A pair of equal values is left as it is.
- Return a list of the same length as
nums. You may reordernumsin place and return it, or return a new list.
Constraints
1 <= len(nums) <= 10^5-10^9 <= nums[i] <= 10^9
Examples
Example 1
Input: nums = [5, 4, 2, 3, 7]
Output: [4, 5, 2, 3, 7]
The pair (5, 4) becomes (4, 5), the pair (2, 3) is already in order, and 7 has no partner, so it does not move.
Example 2
Input: nums = [9, 1, 8, 2]
Output: [1, 9, 2, 8]
Each pair is sorted on its own. The result as a whole is not sorted, and it should not be.
Example 3
Input: nums = [6]
Output: [6]
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.