KatInterview

457. Circular Array Loop

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to detect a specific type of cycle in a circular array of non-zero integers. Each integer nums[i] represents a forward or backward jump. A valid cycle must satisfy three conditions:

Solution

Circular Array Loop in Python

class Solution:
    def circularArrayLoop(self, nums: List[int]) -> bool:
        n = len(nums)
        if n <= 1:
            return False

        def get_next_index(i: int) -> int:
            # In Python, % operator works as mathematical modulo, so it correctly handles negative numbers.
            return (i + nums[i]) % n

        for i in range(n):
            # If nums[i] is 0, this index has been visited and is part of a
            # path that has been confirmed not to be a valid cycle. Skip it.
            if nums[i] == 0:
                continue

            # Use slow and fast pointers to detect a cycle.
            slow, fast = i, i
            # Determine the direction of movement for this path.
            is_forward = nums[i] > 0

            while True:
                # --- Move slow pointer ---
                slow = get_next_index(slow)
                # Check for path validity (same direction, not a processed path).
                if (nums[slow] > 0) != is_forward or nums[slow] == 0:
                    break
                
                # --- Move fast pointer twice ---
                fast = get_next_index(fast)
                if (nums[fast] > 0) != is_forward or nums[fast] == 0:
                    break
                
                fast = get_next_index(fast)
                if (nums[fast] > 0) != is_forward or nums[fast] == 0:
                    break

                # --- Check for cycle ---
                if slow == fast:
                    # Cycle detected. Check if its length is greater than 1.
                    if get_next_index(slow) == slow:
                        # Self-loop of length 1, not a valid cycle.
                        break
                    else:
                        # Valid cycle found.
                        return True
            
            # Path from i is not a valid cycle. Mark visited nodes as 0.
            curr = i
            path_is_forward = nums[i] > 0 # Use this as nums[i] will be modified
            while nums[curr] != 0 and (nums[curr] > 0) == path_is_forward:
                next_node = get_next_index(curr)
                nums[curr] = 0 # Mark as visited
                curr = next_node

        return False

Circular Array Loop in Java

class Solution {
    public boolean circularArrayLoop(int[] nums) {
        int n = nums.length;
        if (n <= 1) {
            return false;
        }

        for (int i = 0; i < n; i++) {
            // Skip already visited/processed nodes
            if (nums[i] == 0) {
                continue;
            }

            int slow = i, fast = i;
            boolean isForward = nums[i] > 0;

            while (true) {
                // Move slow pointer
                slow = getNextIndex(nums, slow, n);
                if ((nums[slow] > 0) != isForward || nums[slow] == 0) {
                    break;
                }

                // Move fast pointer
                fast = getNextIndex(nums, fast, n);
                if ((nums[fast] > 0) != isForward || nums[fast] == 0) {
                    break;
                }
                fast = getNextIndex(nums, fast, n);
                if ((nums[fast] > 0) != isForward || nums[fast] == 0) {
                    break;
                }

                if (slow == fast) {
                    // Cycle detected. Check if length > 1.
                    if (getNextIndex(nums, slow, n) == slow) {
                        // Self-loop, invalid.
                        break;
                    } else {
                        // Valid cycle found.
                        return true;
                    }
                }
            }

            // Path from i is not a valid cycle. Mark visited nodes as 0.
            int curr = i;
            while (nums[curr] != 0 && (nums[curr] > 0) == isForward) {
                int nextNode = getNextIndex(nums, curr, n);
                nums[curr] = 0; // Mark as visited
                curr = nextNode;
            }
        }

        return false;
    }

    private int getNextIndex(int[] nums, int i, int n) {
        // Handle positive and negative jumps in a circular array
        int next = (i + nums[i]) % n;
        return next >= 0 ? next : next + n;
    }
}

Circular Array Loop in C++

class Solution {
public:
    bool circularArrayLoop(vector<int>& nums) {
        int n = nums.size();
        if (n <= 1) {
            return false;
        }

        auto get_next_index = [&](int i) {
            // Handle positive and negative jumps in a circular array
            int next = (i + nums[i]) % n;
            return next >= 0 ? next : next + n;
        };

        for (int i = 0; i < n; ++i) {
            // Skip already visited/processed nodes
            if (nums[i] == 0) {
                continue;
            }

            int slow = i, fast = i;
            bool is_forward = nums[i] > 0;

            while (true) {
                // Move slow pointer
                slow = get_next_index(slow);
                if ((nums[slow] > 0) != is_forward || nums[slow] == 0) break;

                // Move fast pointer
                fast = get_next_index(fast);
                if ((nums[fast] > 0) != is_forward || nums[fast] == 0) break;
                fast = get_next_index(fast);
                if ((nums[fast] > 0) != is_forward || nums[fast] == 0) break;

                if (slow == fast) {
                    // Cycle detected. Check if length > 1.
                    if (get_next_index(slow) == slow) {
                        // Self-loop, invalid.
                        break;
                    } else {
                        // Valid cycle found.
                        return true;
                    }
                }
            }

            // Path from i is not a valid cycle. Mark visited nodes as 0.
            int curr = i;
            while (nums[curr] != 0 && (nums[curr] > 0) == is_forward) {
                int next_node = get_next_index(curr);
                nums[curr] = 0; // Mark as visited
                curr = next_node;
            }
        }

        return false;
    }
};

Circular Array Loop in TypeScript

function circularArrayLoop(nums: number[]): boolean {
    const n = nums.length;
    if (n <= 1) {
        return false;
    }

    const getNextIndex = (i: number): number => {
        // Handle positive and negative jumps in a circular array
        const next = (i + nums[i]) % n;
        return next >= 0 ? next : next + n;
    };

    for (let i = 0; i < n; i++) {
        // Skip already visited/processed nodes
        if (nums[i] === 0) {
            continue;
        }

        let slow = i, fast = i;
        const isForward = nums[i] > 0;

        while (true) {
            // Move slow pointer
            slow = getNextIndex(slow);
            if ((nums[slow] > 0) !== isForward || nums[slow] === 0) break;

            // Move fast pointer
            fast = getNextIndex(fast);
            if ((nums[fast] > 0) !== isForward || nums[fast] === 0) break;
            fast = getNextIndex(fast);
            if ((nums[fast] > 0) !== isForward || nums[fast] === 0) break;

            if (slow === fast) {
                // Cycle detected. Check if length > 1.
                if (getNextIndex(slow) === slow) {
                    // Self-loop, invalid.
                    break;
                } else {
                    // Valid cycle found.
                    return true;
                }
            }
        }

        // Path from i is not a valid cycle. Mark visited nodes as 0.
        let curr = i;
        while (nums[curr] !== 0 && (nums[curr] > 0) === isForward) {
            const nextNode = getNextIndex(curr);
            nums[curr] = 0; // Mark as visited
            curr = nextNode;
        }
    }

    return false;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.