Problem 280891 · easy · Phase 02 Linear Data Structures

Swap Every Pair

arrays · indexing · iteration

Given a list nums, return a new list in which the elements at positions 0 and 1 are swapped, the elements at positions 2 and 3 are swapped, and so on. If the length is odd, the final element has no partner and stays in place.

Examples

Input:  nums = [1, 2, 3, 4, 5]
Output: [2, 1, 4, 3, 5]

Input:  nums = [1, 2, 3, 4]
Output: [2, 1, 4, 3]

Constraints

  • 0 <= len(nums) <= 10**5
  • Return a new list; do not modify nums.
  • Target: O(n) time.

Goals

  • Step through a list two elements at a time
  • Swap values with tuple assignment
  • Leave an unpaired last element alone
Starting Python…