You're out of free questions.

Upgrade now

Write a function that takes a string and reverses the letters in place.

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.

function reverse(&$str) { $leftIndex = 0; $rightIndex = strlen($str) - 1; while ($leftIndex < $rightIndex) { // swap characters $temp = $str[$leftIndex]; $str[$leftIndex] = $str[$rightIndex]; $str[$rightIndex] = $temp; // move towards middle $leftIndex++; $rightIndex--; } }

There is one caveat when using strings as arrays of characters in PHP (so we can do the in-place swapping) - the array we work with is actually an array of bytes, not an array of characters. So if the input is a multi-byte string (for example, an UTF-8 encoded unicode string that contains letters from a non-English alphabet), $str[0] would give us just the first byte of the string, which might not be the full character. If we modify it, we would end up with gibberish.

Therefore it's a good idea to discuss with your interviewer if your code needs to handle multi-byte strings properly (in which case the given solution won't work, and you would need to split the string into individual multi-byte characters first which is no longer in place).

In this case, we are treating the input string as a regular ascii string (one byte per character) to stay in the spirit of the question.

time and space.

Reset editor

Powered by qualified.io

. . .