Swift TLE for problem 874. Walking Robot Simulation

I try tu run my swift code but it keeps complaining about Time Limit Exceeded. I think the algorithm is right. I have found similar algorithms written in C++ that passes.

class Solution {
    var directions = [[0,1],[1,0],[0,-1],[-1,0]]
    func robotSim(_ commands: [Int], _ obstacles: [[Int]]) -> Int {
        var direction = 0
        var position = [0,0]
        var response = 0
        for command in commands {
            if command == -2 {
                direction = (direction + 3) % 4
            }else if command == -1 {
                direction = (direction + 1) % 4
            } else {
                for _ in 0..<command {
                    let tempPosition = [position[0] + directions[direction][0], position[1] + directions[direction][1]]
                    if obstacles.contains(tempPosition) {
                        break
                    }
                    position = tempPosition
                }
            }
            response = max(response, position[0]*position[0] + position[1]*position[1])
        }
        return response
    }
}
Comments (0)