Skip to content

Commit efb40d9

Browse files
committed
Add solution #457
1 parent 8b54638 commit efb40d9

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -365,6 +365,7 @@
365365
454|[4Sum II](./0454-4sum-ii.js)|Medium|
366366
455|[Assign Cookies](./0455-assign-cookies.js)|Easy|
367367
456|[132 Pattern](./0456-132-pattern.js)|Medium|
368+
457|[Circular Array Loop](./0457-circular-array-loop.js)|Medium|
368369
459|[Repeated Substring Pattern](./0459-repeated-substring-pattern.js)|Easy|
369370
461|[Hamming Distance](./0461-hamming-distance.js)|Easy|
370371
463|[Island Perimeter](./0463-island-perimeter.js)|Medium|

solutions/0457-circular-array-loop.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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

Comments
 (0)