Reverse String
Reverse a character array in place using constant extra memory. Preserve spaces and punctuation as characters. Read the input line into the array first.
Work through the cases
3 examplesInput notation
One line of text.Expected result
The characters in reverse order.Case 1
Input
code
Expected output
edoc
Case 2
Input
a b
Expected output
b a
Case 3
Input
x
Expected output
x
These notes use simplified input/output notation. The linked platform defines the method signature and judge format.
FROM IDEA TO IMPLEMENTATION
Understand the approach.
Compare the documented approaches below. Brute force, better, and optimal versions appear where available; a direct exercise may need only one approach.
Reverse a character array in place. A second buffer uses O(n) space. Swapping ends is enough. Two pointers i,j start at the ends, swap, and move inward until they meet. One pass, constant extra space.
We use two pointers i and j, initially pointing to the start and end of the array respectively. Each time, we swap the elements at i and j, then move i forward and j backward, until i and j meet.
The time complexity is O(n), where n is the length of the array. The space complexity is O(1).
class Solution {
public void reverseString(char[] s) {
for (int i = 0, j = s.length - 1; i < j; ++i, --j) {
char t = s[i];
s[i] = s[j];
s[j] = t;
}
}
}Reference code. Platform solutions may use supplied node types, imports, or collection libraries; foundational examples are complete programs.
Solutions adapted from Doocs / LeetCode contributors, licensed under CC BY-SA 4.0. Formatting changed; TypeScript versions converted to JavaScript. Supplemental implementations and approach notes added. Adapted solution material is available under the same license.