1. Auxiliary Array Allocation
Intuition
Create an auxiliary array of size N. Copy characters from s into the new array in reverse order, then overwrite s with the contents of the auxiliary array.
When to apply: Basic baseline comparison.
Algorithm
- Create temporary array
tempof sizen. - For
ifrom 0 ton - 1:temp[i] = s[n - 1 - i]. - For
ifrom 0 ton - 1:s[i] = temp[i].
Auxiliary Array Allocation Trace
2 of 2 questions left todayObservation: Allocate a new array aux of length 5
Observation: Allocate a new array aux of length 5.
Decision: Copy the last element s[4]='o' into aux[0].
Invariant: First element of reversed array established.
#include <iostream>#include <vector> class Solution {public: void reverseString(std::vector<char>& s) { int n = s.size(); std::vector<char> temp(n); for (int i = 0; i < n; ++i) { temp[i] = s[n - 1 - i]; } for (int i = 0; i < n; ++i) { s[i] = temp[i]; } }}; int main() { Solution sol; std::vector<char> s = {'h','e','l','l','o'}; sol.reverseString(s); for (char c : s) std::cout << c << " "; // o l l e h std::cout << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N)— Performs 2N copy assignments and allocates an N-element array. - Space complexity:
O(N) auxiliary space
Why Brute Force Doesn't Scale:
Converging two pointers performs minimal N / 2 operations.
Strict O(1) auxiliary space modifying the input array in-place.