|
4 | 4 | - [Approach 1: Brute Force](#approach-1-brute-force) |
5 | 5 | - [Approach 2: Using Extra Array](#approach-2-using-extra-array) |
6 | 6 | - [Approach 3: Reverse Array](#approach-3-reverse-array) |
| 7 | +- [Approach 4: Two-Point Slice Swap](#approach-4-slice-swap) |
7 | 8 |
|
8 | 9 | ## Approach 1: Brute Force |
9 | 10 |
|
@@ -95,3 +96,45 @@ def rotate(nums, k): |
95 | 96 |
|
96 | 97 | Each approach improves efficiency from the one before, with the third approach being optimal for both time and space. |
97 | 98 |
|
| 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