While exploring algorithms in Swift, couldn\'t find algorithm for array rotation in swift without using funcs shiftLeft
/ shiftRight
.
C has
This solution rotates the element of time complexity O(n)
func rotLeft(a: [Int], d: Int) -> [Int] {
var arr = a
var size = arr.count - 1
for i in 0...size {
let newloc = (i + (arr.count - d)) % arr.count
arr[newloc] = a[i]
}
return arr
}
you shouldn't use .append(x)
as in the worst case it can be
O(n) and you shouldn't use .remove(at: x)
as its O(n) when you can avoid using those methods As when using them you basically get n + n + n which isn't that great