Circular Array Loop — LeetCode 457 Python Solution

MediumArrayHash TableTwo Pointers
Problem
#457
Reading time
4 min

The problem

You are playing a game involving a circular array of non-zero integers nums. Each nums[i] denotes the number of indices forward/backward you must move if you are located at index i: If nums[i] is positive, move nums[i] steps forward, and If nums[i] is negative, move abs(nums[i]) steps backward.

Example

Input
nums = [2,-1,1,2,2]
Output
true
Explanation
The graph shows how the indices are connected. White nodes are jumping forward, while red is jumping backward.

Python solution

Python
class Solution:
    def circularArrayLoop(self, nums: List[int]) -> bool:
        n = len(nums)

        def next(i):
            return (i + nums[i] % n + n) % n

        for i in range(n):
            if nums[i] == 0:
                continue
            slow, fast = i, next(i)
            while nums[slow] * nums[fast] > 0 and nums[slow] * nums[next(fast)] > 0:
                if slow == fast:
                    if slow != next(slow):
                        return True
                    break
                slow, fast = next(slow), next(next(fast))
            j = i
            while nums[j] * nums[next(j)] > 0:
                nums[j] = 0
                j = next(j)
        return False

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 457. Circular Array Loop is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 457. Circular Array Loop?
LeetCode 457. Circular Array Loop is rated Medium on LeetCode.
What is the time complexity of LeetCode 457. Circular Array Loop?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 457. Circular Array Loop?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 457. Circular Array Loop cover?
LeetCode 457. Circular Array Loop is tagged Array, Hash Table and Two Pointers on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview