18. Rotate Array
The problem can be found at the following link: Problem Link
🗳️ Cast Your Vote!
Help shape the future of this repository! Vote now to decide whether I should start adding LeetCode POTD solutions alongside GeeksforGeeks. Your opinion matters! 🌟
Note: I'm currently in the middle of my exams until November 19, so I’ll be uploading daily POTD solutions, but not at a fixed time. Apologies for any inconvenience, and thank you for your patience!
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.
Examples:
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.
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