344. Reverse String
Reverse String asks us to reverse an array of characters in-place. Since the input is already an array, we do not need to create a new reversed array.
Approach
Use one pointer at the start and one pointer at the end:
- Swap the characters at
iandj. - Move
iforward. - Move
jbackward. - Stop when the pointers meet or cross.
Every swap places two characters into their final positions. The middle character in an odd-length array does not need to move.
Swift Notes
The function receives s as inout [Character], which means changes are applied directly to the caller's array. Swift's swapAt method performs the in-place swap clearly and safely.
This is a useful pattern to remember because it also appears in array reversal, palindrome checks, and many two-pointer interview problems.
Complexity
- Time complexity:
O(n). - Space complexity:
O(1).
Edge Cases
- Empty and single-character arrays are already reversed.
- Even-length arrays require all positions to be swapped in pairs.
- Odd-length arrays leave the center character untouched.
swift
class Solution {
func reverseString(_ s: inout [Character]) {
var i = 0
var j = s.count - 1
while i < j {
s.swapAt(i, j)
i = i + 1
j = j - 1
}
}
}
var solution = Solution()
var testcase1: [Character] = ["h","e","l","l","o"]
solution.reverseString(&testcase1)
print(testcase1) // ["o","l","l","e","h"]
var testcase2: [Character] = ["H","a","n","n","a","h"]
solution.reverseString(&testcase2)
print(testcase2) // ["h","a","n","n","a","H"]