|
| 1 | +/** |
| 2 | + * 457. Circular Array Loop |
| 3 | + * https://leetcode.com/problems/circular-array-loop/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are playing a game involving a circular array of non-zero integers nums. Each nums[i] |
| 7 | + * denotes the number of indices forward/backward you must move if you are located at index i: |
| 8 | + * - If nums[i] is positive, move nums[i] steps forward, and |
| 9 | + * - If nums[i] is negative, move nums[i] steps backward. |
| 10 | + * |
| 11 | + * Since the array is circular, you may assume that moving forward from the last element puts |
| 12 | + * you on the first element, and moving backwards from the first element puts you on the last |
| 13 | + * element. |
| 14 | + * |
| 15 | + * A cycle in the array consists of a sequence of indices seq of length k where: |
| 16 | + * - Following the movement rules above results in the repeating index sequence seq[0] -> seq[1] |
| 17 | + * -> ... -> seq[k - 1] -> seq[0] -> ... |
| 18 | + * - Every nums[seq[j]] is either all positive or all negative. |
| 19 | + * - k > 1 |
| 20 | + * |
| 21 | + * Return true if there is a cycle in nums, or false otherwise. |
| 22 | + */ |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {number[]} nums |
| 26 | + * @return {boolean} |
| 27 | + */ |
| 28 | +var circularArrayLoop = function(nums) { |
| 29 | + const n = nums.length; |
| 30 | + |
| 31 | + for (let i = 0; i < n; i++) { |
| 32 | + if (dfs(i, i, nums[i] > 0)) return true; |
| 33 | + } |
| 34 | + |
| 35 | + return false; |
| 36 | + |
| 37 | + function dfs(current, prev, flag) { |
| 38 | + if (nums[current] === 0) return current != prev; |
| 39 | + if (flag != (nums[current] > 0)) return false; |
| 40 | + const moves = nums[current]; |
| 41 | + nums[current] = 0; |
| 42 | + const next = (current + (moves % n) + n) % n; |
| 43 | + const result = dfs(next, current, flag); |
| 44 | + nums[current] = moves; |
| 45 | + return result; |
| 46 | + } |
| 47 | +}; |
0 commit comments