1. Brute Force — Shift by 1 Step k Times
Intuition
In each step, save the last element and shift all elements one index to the right, placing the last element at index 0.
Algorithm
- Initialize required state variables and allocate data structures for Brute Force — Shift by 1 Step k Times.
- Iterate through the input array and apply the core algorithmic condition.
- Update boundaries, frequencies, or pointers in accordance with the invariant.
- Return the computed result or transformed array.
Brute Force Single Step Right Shift Trace (k Times)
2 of 2 questions left todayRotation 1 of 3: Element 7 wraps to front
Rotation 1 of 3: Element 7 wraps to front. All other elements shift right by 1 position.
#include <iostream>#include <vector> using namespace std; class Solution {public: void rotate(vector<int>& nums, int k) { int n = nums.size(); k = k % n; for (int step = 0; step < k; ++step) { int last = nums[n - 1]; for (int i = n - 1; i > 0; --i) { nums[i] = nums[i - 1]; } nums[0] = last; } }}; int main() { Solution sol; vector<int> nums = {1, 2, 3, 4, 5, 6, 7}; int k = 3; cout << "Initial: "; for (int x : nums) cout << x << " "; cout << "\n"; sol.rotate(nums, k); cout << "Rotated: "; for (int x : nums) cout << x << " "; cout << "\n"; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Time complexity for Brute Force — Shift by 1 Step k Times. - Space complexity:
O(1)— Space complexity for Brute Force — Shift by 1 Step k Times.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.