You are given a string as a list of single characters, s. Reverse it: when you are done, the first character must be the old last one, the second the old second-to-last, and so on.
Change s itself instead of returning a new list, and use only a constant amount of extra memory, no matter how long s is. The function returns nothing.
Example 1
Input: s = ["p","l","a","n","e","t"] Output: ["t","e","n","a","l","p"] Why: the last character comes first, and so on
2 more examples and the constraints
Example 2
Input: s = ["N","o","o","n"] Output: ["n","o","o","N"] Why: case is kept; only positions change
Example 3
Input: s = ["a","b"," ","?"] Output: ["?"," ","b","a"] Why: spaces and symbols are characters too
Constraints
- 1 ≤ length of s ≤ 100,000
- Every s[i] is a printable ASCII character (letters, digits, spaces, symbols)
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Reversed copyO(n)
- Swap from both endsO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Extra memory for 100,000 characters | Verdict |
|---|---|---|---|
| Reversed copy | O(n) | Correct, but uses O(n) extra memory | |
| Swap from both ends | O(n) | Best; in place, two counters |
n = length of s. Both are linear in time; the bars compare the extra memory.
Edge cases to test
- One character.
left = right = 0, so the loop never runs andsstays as it is. - Odd length. In "abcde" the middle
cis never swapped; the pointers meet on it and stop. - Even length. In "ok" one swap is made, then
left = 1andright = 0cross and the loop ends. - Symbols and spaces. Quotes, spaces and punctuation are ordinary characters and move like letters.
Common mistakes
- Looping while
left <= rightor over the whole length, which swaps pairs twice and undoes the work. - Returning a reversed copy instead of changing
s, so the caller still sees the old order. - Swapping with
s[n - i]instead ofs[n - 1 - i], which reads one past the end.
How to talk through it
- 1Clarify. Do I change
sin place and return nothing? Is a single character allowed? - 2Name the easy way. A reversed copy written back works in O(n) time, but it needs O(n) extra memory.
- 3Pair up mirrors. Index
iand indexn − 1 − itrade places, so two pointers from the ends can swap pair by pair. - 4State the cost. n / 2 swaps, O(n) time, and only two counters, so O(1) extra space.
- 5Test out loud. Run one character, an even length like "ok", and an odd one like "abcde".
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?