How to Rotate an Array in O(n) Time and O(1) Space

View profile for Aashi Dagar

2nd year ||B-Tech|| CSE|| At Uttaranchal University , Dehradun 🎓'2027 UIT

Problem: 189. Rotate Array Approach We need to rotate the array nums to the right by k steps. That means every element at index i should move to (i + k) % n, where n is the size of the array. Key Idea: Reverse Technique Instead of shifting elements one by one (which is inefficient), we can use the reverse method: Since rotating n times gives the same array, we only need k = k % n. Reverse operations: Reverse the first n - k elements. Reverse the last k elements. Reverse the entire array. This ensures that the last k elements come to the front while maintaining the correct order. Example Input: nums = [1,2,3,4,5,6,7], k = 3 Steps: Reverse first 4 → [4,3,2,1,5,6,7] Reverse last 3 → [4,3,2,1,7,6,5] Reverse whole → [5,6,7,1,2,3,4] Output: [5,6,7,1,2,3,4] ✅ Complexity Analysis Time Complexity: Each reversal takes O(n). Total = O(n). Space Complexity: In-place reversal, no extra array used. Total = O(1). ✅ This is the optimal solution with O(n) time and O(1) space. #DSA #DAY3

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories