Only case 4 gives runtime error. I looked at other answers but couldn't find a solution
I don't return the array. I'm just adding elements
func circularArrayRotation(a: [Int], k: Int, queries: [Int]) -> [Int] {
var result = [Int]()
for i in queries {
if i < k {
result.append(a[a.count-k+i])
}
else {
result.append(a[i-k])
}
}
return result
}
Isn't the time complexity of this algorithm O(n). Am I calculating wrong?
k
can be much larger than the length of the array, so your approach is failing since the index is much larger than the array length.
To correctly handle this, make k
equal to k modulus array_length
, since rotating the array by array_length
times effectively makes no changes to the current ordering.