Day 4 - Rotate Array
π Day 4. Rotate Array π§
The problem can be found at the following link: Problem Link
π‘ Problem Description:
Given an unsorted array arr[]. Rotate the array to the left (counter-clockwise direction) by d steps, where d is a positive integer. Do the mentioned change in the array in place.
Note: Consider the array as circular.
π Example Walkthrough:
Input:
arr[] = [1, 2, 3, 4, 5], d = 2
Output:
[3, 4, 5, 1, 2]
Explanation:
When rotated by 2 elements, it becomes [3, 4, 5, 1, 2].
Input:
arr[] = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20], d = 3
Output:
[8, 10, 12, 14, 16, 18, 20, 2, 4, 6]
Explanation:
When rotated by 3 elements, it becomes [8, 10, 12, 14, 16, 18, 20, 2, 4, 6].
Input:
arr[] = [7, 3, 9, 1], d = 9
Output:
[3, 9, 1, 7]
Explanation:
When we rotate 9 times, we'll get [3, 9, 1, 7] as the resultant array.
Constraints:
1 <= arr.size(), d <= 10^50 <= arr[i] <= 10^5
π― My Approach:
Rotation Process:
The idea is to rotate the array in three parts by reversing the elements in each part:
Reverse the first
delements.Reverse the remaining elements from index
dton-1.Reverse the entire array to get the final rotated array.
This way, we achieve the desired result without using extra space.
Steps:
First, we reverse the first
delements.Then, reverse the rest of the array (from index
dton-1).Finally, reverse the entire array.
π Time and Auxiliary Space Complexityπ
Expected Time Complexity: O(n), where
nis the number of elements in the array. We perform constant-time operations like swapping elements, each occurring at mostntimes.Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for temporary variables.
π Solution Code
Code (C)
Code (Cpp)
Code (Java)
Code (Python)
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated