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 strings in place. Since we're modifying the input, we need a mutable type like an array, instead of Objective-C's immutable strings.

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.

void ICKReverse(unichar *arrayOfChars, NSUInteger length) { if (length == 0) { return; } NSUInteger leftIndex = 0; NSUInteger rightIndex = length - 1; while (leftIndex < rightIndex) { // swap characters unichar leftChar = arrayOfChars[leftIndex]; arrayOfChars[leftIndex] = arrayOfChars[rightIndex]; arrayOfChars[rightIndex] = leftChar; // move towards middle leftIndex++; rightIndex--; } }

time and space.

Reset editor

Powered by qualified.io

. . .