[Question]: Reverse a string with O(1) extra memory. The input string is given as an array of characters like [“C”, “A”, “R”]
func makeReverseArray(_ s: inout [Character]) {
for i in 0..<s.count/2 {
//s.swapAt(s.count - i - 1, i) // by using Apple's predefined function.
(s[i],s[s.count - i - 1]) = (s[s.count - i - 1],s[i])
}
}
var charsInput:[Character] = ["C","A", "R"]
makeReverseArray(&charsInput)
print("output-->", charsInput) // Prints ["R", "A", "C"]
So here we have used one for loop which iterates half of array & swapping last with first