LeetCode in Kotlin

2120. Execution of All Suffix Instructions Staying in a Grid

Medium

There is an n x n grid, with the top-left cell at (0, 0) and the bottom-right cell at (n - 1, n - 1). You are given the integer n and an integer array startPos where startPos = [startrow, startcol] indicates that a robot is initially at cell (startrow, startcol).

You are also given a 0-indexed string s of length m where s[i] is the ith instruction for the robot: 'L' (move left), 'R' (move right), 'U' (move up), and 'D' (move down).

The robot can begin executing from any ith instruction in s. It executes the instructions one by one towards the end of s but it stops if either of these conditions is met:

Return an array answer of length m where answer[i] is the number of instructions the robot can execute if the robot begins executing from the ith instruction in s.

Example 1:

Input: n = 3, startPos = [0,1], s = “RRDDLU”

Output: [1,5,4,3,1,0]

Explanation: Starting from startPos and beginning execution from the ith instruction:

Example 2:

Input: n = 2, startPos = [1,1], s = “LURD”

Output: [4,1,0,0]

Explanation:

Example 3:

Input: n = 1, startPos = [0,0], s = “LRUD”

Output: [0,0,0,0]

Explanation: No matter which instruction the robot begins execution from, it would move off the grid.

Constraints:

Solution

class Solution {
    fun executeInstructions(n: Int, startPos: IntArray, s: String): IntArray {
        val answer = IntArray(s.length)
        for (i in 0 until s.length) {
            var count = 0
            var currX = startPos[0]
            var currY = startPos[1]
            for (j in i until s.length) {
                val mv = s[j]
                if (mv == 'R') {
                    currY++
                    if (currY > n - 1) {
                        break
                    }
                } else if (mv == 'D') {
                    currX++
                    if (currX > n - 1) {
                        break
                    }
                } else if (mv == 'L') {
                    currY--
                    if (currY < 0) {
                        break
                    }
                } else if (mv == 'U') {
                    currX--
                    if (currX < 0) {
                        break
                    }
                }
                count++
            }
            answer[i] = count
        }
        return answer
    }
}