You're out of free questions.

Upgrade now

Write a function that takes an array of characters and reverses the letters in place.

Why an array of characters instead of a string?

The goal of this question is to practice manipulating arrays in place. Since Swift strings support unicode, a single character in a string might be multiple bytes. There's no way to get the ith character in a Swift string.

To sidestep this complexity, we'll work with arrays of characters instead, which let us quickly access characters at any offset.

In general, an in-place algorithm will require swapping elements.

We swap the first and last characters, then the second and second-to-last characters, and so on until we reach the middle.

func reverse(_ str: inout [Character]) { guard str.count > 0 else { return } var leftIndex = 0 var rightIndex = str.count - 1 while leftIndex < rightIndex { // swap characters let leftChar = str[leftIndex] let rightChar = str[rightIndex] str[leftIndex] = rightChar str[rightIndex] = leftChar // move towards middle leftIndex += 1 rightIndex -= 1 } }

time and space.

Reset editor

Powered by qualified.io

. . .