Skip to main content

DSA: Reverse a String from an Index

DSA

Manually reverse a Swift string suffix from any character offset with two pointers.

Convert the string to [Character], then swap inward from the requested offset and the end. The start value is a zero-based character offset, and passing characters.count is a valid no-op.

func reverse(_ characters: inout [Character], from start: Int) {
    precondition((0...characters.count).contains(start))

    var left = start
    var right = characters.count - 1

    while left < right {
        characters.swapAt(left, right)
        left += 1
        right -= 1
    }
}

var characters = Array("abcdef")
reverse(&characters, from: 2)

let result = String(characters)
// "abfedc"

The two-pointer pass takes linear time over the reversed suffix and uses constant extra space after the string has been converted to an array.