Swift
Rotate Array
Array Manipulation
Programming
Swift Tips

Rotate Array in Swift

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Rotating an array means shifting elements left or right and wrapping the overflow back to the opposite end. In Swift, the most important design choice is whether you want a new rotated array or an in-place mutation of the existing buffer.

Normalize the Rotation Count First

Every correct implementation starts by normalizing the shift. A rotation by the array length changes nothing, and negative values are usually best interpreted as rotation in the opposite direction.

For example, on [1, 2, 3, 4, 5]:

  • rotate right by 2 gives [4, 5, 1, 2, 3]
  • rotate left by 2 gives [3, 4, 5, 1, 2]
  • rotate right by 7 is the same as rotate right by 2

This normalization formula handles those cases:

swift
let shift = ((positions % array.count) + array.count) % array.count

The extra addition before the final modulo is what makes negative values work cleanly.

Return a New Array with Slicing

If mutation is not required, slicing is usually the clearest approach. It reads almost like the definition of the operation.

swift
1func rotatedRight<T>(_ array: [T], by positions: Int) -> [T] {
2    guard !array.isEmpty else { return [] }
3
4    let shift = ((positions % array.count) + array.count) % array.count
5    guard shift != 0 else { return array }
6
7    let split = array.count - shift
8    return Array(array[split...]) + Array(array[..<split])
9}
10
11let values = [1, 2, 3, 4, 5]
12print(rotatedRight(values, by: 2))
13print(rotatedRight(values, by: -1))

This version is generic, easy to test, and fits well with Swift's value-oriented style. It allocates a new array, which is often perfectly acceptable in application code.

Rotate In Place with the Reversal Method

If you want to mutate the array without allocating another full copy, use the classic reversal algorithm. The idea is:

  1. Reverse the whole array.
  2. Reverse the prefix that should end up at the front.
  3. Reverse the remainder.
swift
1func rotateInPlace<T>(_ array: inout [T], by positions: Int) {
2    guard !array.isEmpty else { return }
3
4    let shift = ((positions % array.count) + array.count) % array.count
5    guard shift != 0 else { return }
6
7    array.reverse()
8    array[0..<shift].reverse()
9    array[shift..<array.count].reverse()
10}
11
12var items = [1, 2, 3, 4, 5, 6]
13rotateInPlace(&items, by: 2)
14print(items)

This runs in O(n) time and uses little extra storage. It is the usual answer when the task specifically asks for in-place rotation.

Left Rotation Does Not Need a Separate Algorithm

Once the shift is normalized, one function can handle both directions. A negative right rotation is the same as a positive left rotation.

swift
let original = [10, 20, 30, 40, 50]
print(rotatedRight(original, by: -2))
print(rotatedRight(original, by: 3))

Those two calls produce the same result. This is a good reason not to maintain separate code paths unless the API explicitly wants different function names for readability.

Choose the API That Matches Ownership

There is no universal best implementation. The correct choice depends on the surrounding code.

Return a new array when:

  • callers expect immutability
  • the array is small or medium sized
  • readability matters more than squeezing out one allocation

Mutate in place when:

  • the array is large
  • rotation happens in a tight loop
  • the caller already owns the buffer and expects mutation

Swift code is often cleaner when functions are honest about ownership. Avoid in-place mutation just because it sounds more algorithmic.

Common Pitfalls

  • Forgetting modulo normalization, which makes large shift values behave incorrectly.
  • Ignoring negative shifts and then writing a second function for left rotation.
  • Mutating an array in place when the caller expected the original value to remain unchanged.
  • Forgetting the empty-array guard, which makes index arithmetic crash.
  • Overcomplicating the solution when slicing is already clear enough for the problem size.

Summary

  • Array rotation is a wrapped shift of elements left or right.
  • Normalize the shift so large and negative values behave correctly.
  • Slicing is the clearest way to return a rotated copy.
  • The reversal method is the standard in-place O(n) solution.
  • Pick the version that matches the ownership and performance needs of the caller.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.