일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 코드업
- heap
- 파이썬알고리즘
- GenerativeAI
- 생성형AI
- 슬라이딩윈도우
- Python3
- stratascratch
- 투포인터
- 파이썬기초100제
- codeup
- LeetCode
- medium
- SQL
- 니트코드
- GenAI
- slidingwindow
- 리트코드
- nlp
- 자연어처리
- 파이썬
- 릿코드
- tree
- sql코테
- 알고리즘
- gcp
- Python
- Stack
- two-pointer
- dfs
Archives
- Today
- Total
Tech for good
[Leetcode/TwoPointer] 189. Rotate Array 본문
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
n = len(nums)
k = k % n # In case k is larger than n
# Step 1: Reverse the entire array
nums.reverse()
# Step 2: Reverse the first k elements
nums[:k] = reversed(nums[:k])
# Step 3: Reverse the remaining n-k elements
nums[k:] = reversed(nums[k:])
Explanation
For nums = [1,2,3,4,5,6,7] and k = 3:
- Reverse entire array: [7,6,5,4,3,2,1]
- Reverse first k elements (k=3): [5,6,7,4,3,2,1]
- Reverse remaining part: [5,6,7,1,2,3,4]
✅ Time Complexity: O(n)
✅ Space Complexity: O(1) (modifies the array in-place)
- In case of (n = k), nums = output
- However, in case of k >= n, k = spare of (k % n)