
Problem
Solution
Submissions
Rotate an Array by k Positions to the Right
Certification: Basic Level
Accuracy: 100%
Submissions: 3
Points: 5
Write a C# program to implement the RotateArray(int[] nums, int k) function, which rotates an array of integers to the right by k steps, where k is a non-negative integer.
Algorithm
- Step 1: Handle the case where k is larger than the array length by using modulo: k = k % nums.Length
- Step 2: Rotate the entire array.
- Step 3: Rotate the first k elements.
- Step 4: Rotate the remaining elements (from index k to the end).
Example 1
- Input: nums = [1,2,3,4,5,6,7], k = 3
- Output: [5,6,7,1,2,3,4]
- Explanation:
- Rotate 1 steps to the right: [7,1,2,3,4,5,6]
- Rotate 2 steps to the right: [6,7,1,2,3,4,5]
- Rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2
- Input: nums = [1,2], k = 5
- Output: [2,1]
- Explanation:
- Since k=5 and array length is 2, k % array.length = 5 % 2 = 1
- Rotate 1 step to the right: [2,1]
Constraints
- 1 ≤ nums.length ≤ 10^5
- -2^31 ≤ nums[i] ≤ 2^31 - 1
- 0 ≤ k ≤ 10^5
- Time Complexity: O(n) where n is the length of the array
- Space Complexity: O(1) - should be done in-place
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use the reverse array technique to achieve rotation with O(1) extra space.
- Remember to handle the case when k > array length.
- Break the problem into smaller steps: reverse the entire array, then reverse the first k elements, then reverse the rest.
- Alternatively, you can use a temporary array if space complexity is not a concern.