Skip to content

Prefix-Suffix Swap

01 · Question

We are given an array of letters, arr, and a length, n, which is a multiple of 3. The goal is to modify arr in place to move the prefix of length n/3 to the end and the suffix of length n/3 to the beginning.

Example:

  • Input: arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
  • Output: ['G', 'H', 'I', 'D', 'E', 'F', 'A', 'B', 'C']

02 · Solution

Reference solution

1def prefixSuffixSwap(arr: List[str]) -> None:
2 n = len(arr)
3 k = n // 3
4 l, r = 0, n - k
5
6 while l < k:
7 arr[l], arr[r] = arr[r], arr[l]
8 l += 1
9 r += 1