Search code examples
swiftalgorithmruntime-error

I'm working on the algorithm and it only gives an error in 1 case (Runtime Error)


Only case 4 gives runtime error. I looked at other answers but couldn't find a solution

Question

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?

case ss


Solution

  • 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.