Skip to content

Commit e07e701

Browse files
authored
Update rotate-array.md
1 parent bc1f2e2 commit e07e701

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

python/rotate-array.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
- [Approach 1: Brute Force](#approach-1-brute-force)
55
- [Approach 2: Using Extra Array](#approach-2-using-extra-array)
66
- [Approach 3: Reverse Array](#approach-3-reverse-array)
7+
- [Approach 4: Two-Point Slice Swap](#approach-4-slice-swap)
78

89
## Approach 1: Brute Force
910

@@ -95,3 +96,45 @@ def rotate(nums, k):
9596

9697
Each approach improves efficiency from the one before, with the third approach being optimal for both time and space.
9798

99+
## Approach 4: Two-Point Python Slice Swap
100+
101+
### Intuition
102+
103+
When rotating an array by k positions to the right, we're essentially splitting the array into two parts and swapping their positions. The last k elements move to the front, while the remaining elements shift to the end.
104+
105+
### Approach
106+
107+
1. First, we handle edge cases:
108+
- If k is larger than array length, we only need to rotate by k % len(nums)
109+
- If array has 0-1 elements or k = 0, no rotation needed
110+
2. The main logic uses Python's slice assignment feature:
111+
- `nums[-k:]` takes the last k elements
112+
- `nums[:-k]` takes all elements except the last k
113+
- We assign these slices to `nums[:k]` (first k positions) and `nums[k:]` (remaining positions) respectively
114+
115+
For example, with nums = [1,2,3,4,5] and k = 2:
116+
117+
- `nums[-k:]` is [4,5]
118+
- `nums[:-k]` is [1,2,3]
119+
- After assignment: [4,5,1,2,3]
120+
121+
```python
122+
class Solution:
123+
def rotate(self, nums: List[int], k: int) -> None:
124+
"""
125+
Do not return anything, modify nums in-place instead.
126+
"""
127+
k = k % len(nums)
128+
129+
if len(nums) <= 1 or k == 0:
130+
return
131+
132+
nums[:k], nums[k:] = nums[-k:], nums[:-k]
133+
```
134+
135+
### Complexity
136+
137+
- Time complexity: $$O(n)$$
138+
- Creating slices and copying elements requires traversing the array once
139+
- Space complexity: $$O(1)$$
140+
- While Python's slice assignment creates temporary lists internally, the problem considers this as constant space since we're using language features rather than explicitly creating additional data structures

0 commit comments

Comments
 (0)