Skip to content

Instantly share code, notes, and snippets.

@froggomad
Last active February 19, 2020 16:41
Show Gist options
  • Save froggomad/a1df7790fcb2311a24934d6d426b6cd3 to your computer and use it in GitHub Desktop.
Save froggomad/a1df7790fcb2311a24934d6d426b6cd3 to your computer and use it in GitHub Desktop.
Rotate an array (k) positions
/*:
## Given an array, rotate the array to the right by k steps, where k is non-negative.
```
Example 1:
Input: [1,2,3,4,5,6,7] and k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
```
```
Example 2:
Input: [-1,-100,3,99] and k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
```
*/
func rotate<a>(arr: inout[a], steps k: Int) {
if k > 0 {
for _ in 1...k { //do the following k times
let last = arr.last! //save the last position of the array to move it to the first position
for i in (1..<arr.count).reversed() { //loop through the array backwards
arr[i] = arr[i - 1] //shift 1 position to the right
}
arr[0] = last //replace the first array position with the original last array position
}
} else {
print("Enter a positive integer")
}
}
var arr = [0,1,2,3,4,5]
rotate(arr: &arr, steps: 3)
var letterArr = ["a","b","c"]
rotate(arr: &letterArr, steps: 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment