Reverse a Character Array In Place with Constant Extra Memory
SnowflakeSoftware Engineer · Technical ScreenLast updated
Reverse a string given as an array of characters in place, using only constant extra memory, and return the same list. A short coding warm-up that tests index handling, swapping elements and odd and even lengths without building a copy.
Reverse a string given as an array of its characters. The reversal must happen in place: rearrange the elements of the given list itself, using only a constant amount of extra memory, and return that list.
Function Signature
def reverse_characters(chars: list[str]) -> list[str]:
Rules
- Modify
charsitself. Do not build a reversed copy, and do not call a built-in reverse routine or use slicing that creates a new list. - Return the same list object after the reversal.
Constraints
1 <= len(chars) <= 10^5- every element is a single printable ASCII character (codes 32 to 126); spaces and punctuation are ordinary characters
Examples
Example 1
Input: chars = ["h", "e", "l", "l", "o"]
Output: ["o", "l", "l", "e", "h"]
Example 2
Input: chars = ["a", " ", "b", "!"]
Output: ["!", "b", " ", "a"]
With an even length, every element moves; the space is reversed like any other character.
Example 3
Input: chars = ["z"]
Output: ["z"]
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.