Reverse String
Problem Statement
Write a function that reverses a string. The input string is given as an array of characters s.
You must do this by modifying the input array in-place with minimal extra memory usage.
Method Signature
Java
public static void reverseString(char[] s)
Examples
Example 1:
Input: s = ['h','e','l','l','o']
Output: ['o','l','l','e','h']
Example 2:
Input: s = ['H','a','n','n','a','h']
Output: ['h','a','n','n','a','H']
Example 3:
Input: s = ['A']
Output: ['A']
Explanation: Single character remains unchanged
Example 4:
Input: s = ['a','b']
Output: ['b','a']
Explanation: Two characters swap positions
Test Your Solution
Java
import java.util.Arrays;
public class ReverseStringTest {
public static void main(String[] args) {
// Test case 1
char[] test1 = {'h','e','l','l','o'};
System.out.println("Before: " + Arrays.toString(test1));
reverseString(test1);
System.out.println("After: " + Arrays.toString(test1)); // Expected: [o, l, l, e, h]
// Test case 2
char[] test2 = {'H','a','n','n','a','h'};
System.out.println("Before: " + Arrays.toString(test2));
reverseString(test2);
System.out.println("After: " + Arrays.toString(test2)); // Expected: [h, a, n, n, a, H]
// Test case 3 - Single character
char[] test3 = {'A'};
System.out.println("Before: " + Arrays.toString(test3));
reverseString(test3);
System.out.println("After: " + Arrays.toString(test3)); // Expected: [A]
// Test case 4 - Two characters
char[] test4 = {'a','b'};
System.out.println("Before: " + Arrays.toString(test4));
reverseString(test4);
System.out.println("After: " + Arrays.toString(test4)); // Expected: [b, a]
// Test case 5 - Even length
char[] test5 = {'1','2','3','4'};
System.out.println("Before: " + Arrays.toString(test5));
reverseString(test5);
System.out.println("After: " + Arrays.toString(test5)); // Expected: [4, 3, 2, 1]
}
// Your implementation goes here
public static void reverseString(char[] s) {
// TODO: Implement string reversal in-place
}
}
Extension Challenges
- Reverse substring: Reverse only characters from index i to j
- Reverse words: Reverse entire string, then reverse each word individually
- Reverse with exclusions: Skip certain characters (like spaces or punctuation)
- Palindrome check: Modify to check if string reads same forwards and backwards
- Rotate array: Use similar two-pointer technique for array rotation
Real-World Applications
- Text processing: Reversing user input or display strings
- Algorithms: Palindrome detection, string matching
- Data structures: Implementing reverse iterators
- Cryptography: Simple character scrambling (though not secure)
- Game development: Text effects and animations