Skip to content

Commit 19ca95f

Browse files
committed
added Rotate Array (easy)
1 parent d33f0f4 commit 19ca95f

File tree

3 files changed

+69
-0
lines changed

3 files changed

+69
-0
lines changed

Easy/RotateArray/README.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
2+
# Rotate Array
3+
[Leetcode Link](https://leetcode.com/problems/rotate-array/)
4+
5+
## Problem:
6+
7+
Given an array, rotate the array to the right by *k* steps, where *k* is non-negative.
8+
9+
**Follow up:**
10+
11+
- Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
12+
- Could you do it in-place with O(1) extra space?
13+
14+
15+
## Example:
16+
17+
```
18+
Input: nums = [1,2,3,4,5,6,7], k = 3
19+
Output: [5,6,7,1,2,3,4]
20+
Explanation:
21+
rotate 1 steps to the right: [7,1,2,3,4,5,6]
22+
rotate 2 steps to the right: [6,7,1,2,3,4,5]
23+
rotate 3 steps to the right: [5,6,7,1,2,3,4]
24+
```
25+
```
26+
Input: nums = [-1,-100,3,99], k = 2
27+
Output: [3,99,-1,-100]
28+
Explanation:
29+
rotate 1 steps to the right: [99,-1,-100,3]
30+
rotate 2 steps to the right: [3,99,-1,-100]
31+
```
32+
33+
## Note:
34+
35+
- `1 <= nums.length <= 2 * 10^4`
36+
- It's guaranteed that `nums[i]` fits in a 32 bit-signed integer.
37+
- `k >= 0`

Easy/RotateArray/solution.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
from typing import List
2+
3+
class Solution:
4+
def rotate(self, nums: List[int], k: int) -> None:
5+
"""
6+
Do not return anything, modify nums in-place instead.
7+
"""
8+
# rotations repeat in modulo
9+
# k %= len(nums)
10+
i = 0
11+
count = 0
12+
while count < len(nums):
13+
start = i
14+
copy = nums[i]
15+
while True:
16+
j = (i + k) % len(nums) # allows end of array "cycle" back to beginning of array
17+
copy, nums[j] = nums[j], copy
18+
i = j
19+
count += 1
20+
if i == start:
21+
break
22+
i += 1
23+
24+
25+
26+
# test driver
27+
sol = Solution()
28+
nums = [1,2]
29+
k = 3
30+
sol.rotate(nums, k)
31+
print("Output:", nums)

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ Languages used: Java and Python
4141
- [Longest Continuous Increasing Subsequence](Easy/LongestIncreasingSubsequence)
4242
- [Happy Number](Easy/HappyNumber)
4343
- [Assign Cookies](Easy/AssignCookies)
44+
- [Rotate Array](Easy/RotateArray)
4445
- Medium
4546
- [Minimum Add to Make Parentheses Valid](Medium/MinimumAddtoMakeParenthesesValid)
4647
- [Distribute Coins in Binary Tree](Medium/DistributionCoinsInBinaryTree)

0 commit comments

Comments
 (0)