Skip to content

Commit 0390eb8

Browse files
author
Partho Biswas
committed
189. Rotate Array
1 parent 4964490 commit 0390eb8

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,7 @@ I have solved quite a number of problems from several topics. See the below tabl
190190
|76| **[896. Monotonic Array](https://tinyurl.com/y8a95fb6)** | [Python](https://tinyurl.com/wu6rdaw/896_Monotonic_Array.py), [Swift](https://tinyurl.com/wuja3c4/896_Monotonic_Array.swift) | --- | Eassy | |
191191
|77| **[670. Maximum Swap](https://tinyurl.com/y2zhdd33)** | [Python](https://tinyurl.com/wu6rdaw/670_Maximum_Swap.py), [Swift](https://tinyurl.com/wuja3c4/670_Maximum_Swap.swift) | [Art 1](https://tinyurl.com/y8vqklj3) | Medium | |
192192
|78| **[825. Friends Of Appropriate Ages](https://tinyurl.com/ycgnqxb8)** | [Python](https://tinyurl.com/wu6rdaw/825_Friends_Of_Appropriate_Ages.py), [Swift](https://tinyurl.com/wuja3c4/825_Friends_Of_Appropriate_Ages.swift) | [Art 1](https://tinyurl.com/yd4oal3l) | Medium | Think differently from a different angle. Loved this problem |
193+
|79| **[189. Rotate Array](https://tinyurl.com/yalocp9r)** | [Python](https://tinyurl.com/wu6rdaw/189_Rotate_Array.py), [Swift](https://tinyurl.com/wuja3c4/189_Rotate_Array.swift) | --- | Easy | Getting to inplace (O(n) time and O(1) space) solution is tricky. |
193194

194195

195196
</p>
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import Foundation
2+
class Solution {
3+
func rotate(_ nums: inout [Int], _ k: Int) {
4+
var steps = k % nums.count
5+
if steps == 0 {
6+
return
7+
}
8+
nums.reverse()
9+
10+
// Swap first portion
11+
var (left, right) = (0, steps - 1)
12+
while left < right {
13+
nums.swapAt(left, right)
14+
left += 1
15+
right -= 1
16+
}
17+
18+
// Swap last portion
19+
(left, right) = (steps, nums.count - 1)
20+
while left < right {
21+
nums.swapAt(left, right)
22+
left += 1
23+
right -= 1
24+
}
25+
}
26+
}
27+
28+
/*
29+
Input: nums = [1,2,3,4,5,6,7], k = 3
30+
Output: [5,6,7,1,2,3,4]
31+
32+
33+
1,2,3,4, 5,6,7
34+
35+
1,2,3,4, 7,6,5
36+
37+
7,6,5, 4,3,2,1
38+
39+
40+
41+
>5,6,7, 1,2,3,4
42+
43+
>5,6,7,1,2,3,4
44+
*/

0 commit comments

Comments
 (0)