Bird
Raised Fist0
Interview Prepfast-slow-pointersmediumAmazonGoogle

Circular Array Loop

Choose your preparation mode4 modes available
📋
Problem

Imagine a circular conveyor belt with sections moving forward or backward. You want to detect if there's a loop where a package could keep moving endlessly in one direction.

Given a circular array nums of integers, where each element represents the number of steps to move forward (positive) or backward (negative), determine if there is a cycle in the array. The cycle must be strictly longer than 1 element and all steps in the cycle must move in the same direction (all positive or all negative). Return true if such a cycle exists, otherwise false.

1 ≤ nums.length ≤ 10^5-10^5 ≤ nums[i] ≤ 10^5nums[i] ≠ 0
Edge cases: Single element array [1] → false (cycle length must be > 1)All elements same positive number [1,1,1,1] → true (full cycle)Array with zero steps [0,1,2] → invalid input as per constraints
</>
IDE
def circularArrayLoop(nums: list[int]) -> bool:public boolean circularArrayLoop(int[] nums)bool circularArrayLoop(vector<int>& nums)function circularArrayLoop(nums)
def circularArrayLoop(nums):
    # Write your solution here
    pass
class Solution {
    public boolean circularArrayLoop(int[] nums) {
        // Write your solution here
        return false;
    }
}
#include <vector>
using namespace std;

bool circularArrayLoop(vector<int>& nums) {
    // Write your solution here
    return false;
}
function circularArrayLoop(nums) {
    // Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: true for single element arrayFailed to check cycle length > 1, returning true for trivial cycles.✅ Add condition to verify cycle length is strictly greater than 1 before returning true.
Wrong: true for mixed direction cyclesDid not enforce direction consistency within detected cycles.✅ Check that all elements in the cycle have the same sign before confirming cycle.
Wrong: false for valid cycles with negative stepsFailed to detect cycles moving backward or handle negative indices correctly.✅ Use modulo arithmetic carefully and ensure direction consistency check includes negative direction.
Wrong: true for non-cycles due to greedy approachAssumed any forward step forms a cycle without proper cycle detection.✅ Implement fast and slow pointer cycle detection instead of greedy assumptions.
Wrong: TLE on large inputsUsing brute force O(n^2) simulation from each index.✅ Optimize to O(n) fast and slow pointer approach with early exits.
✓
Test Cases
t1_01basic
Input{"nums":[2,-1,1,2,2]}
Expectedtrue

There is a cycle: index 0 -> 2 -> 3 -> 0, all moving forward.

t1_02basic
Input{"nums":[-2,1,-1,-2,-2]}
Expectedtrue

Cycle exists: index 0 -> 3 -> 0 moving backward consistently.

t2_01edge
Input{"nums":[1]}
Expectedfalse

Single element cannot form a cycle longer than 1.

t2_02edge
Input{"nums":[1,1,1,1]}
Expectedtrue

All elements same positive number form a full cycle moving forward.

t2_03edge
Input{"nums":[1,-1,1,-1]}
Expectedfalse

No cycle because direction consistency fails (mixed positive and negative).

t3_01corner
Input{"nums":[3,1,2]}
Expectedfalse

Greedy approach fails here; no valid cycle exists despite multiple jumps.

t3_02corner
Input{"nums":[1,2,3,4,5]}
Expectedtrue

Cycle exists moving forward through all indices; tests 0/1 vs unbounded confusion.

t3_03corner
Input{"nums":[1,2,-1,2,2]}
Expectedtrue

Cycle exists ignoring the negative step that breaks direction consistency if included.

t4_01performance
Input{"nums":[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]}
⏱ Performance - must finish in 2000ms

n=100, O(n) fast-slow pointer cycle detection must complete within 2 seconds.

Practice

(1/5)
1. Given the following Python code for reorderList and the input list 1->2->3->4, what is the value of the node pointed to by left after the first merge step in the recursion unwinding?
easy
A. Node with value 3
B. Node with value 2
C. Node with value 4
D. Node with value 1

Solution

  1. Step 1: Trace recursion to the end

    Recursion reaches right = None, then unwinds from node 4 back to node 1.
  2. Step 2: First merge step during unwinding

    At right=4, left=1, tmp=left.next=2; left.next=4; 4.next=2; left=2 after merge.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    After first merge, left points to node with value 2 [OK]
Hint: left moves forward after merging right node [OK]
Common Mistakes:
  • Confusing left pointer update
  • Off-by-one in recursion unwind
  • Misreading next pointer assignments
2. Identify the bug in the following Python code for checking if a number is happy. The code attempts to detect cycles using recursion but lacks proper cycle detection.
def isHappy(n: int) -> bool:
    def get_next(number):
        total_sum = 0
        while number > 0:
            digit = number % 10
            total_sum += digit * digit
            number //= 10
        return total_sum

    def helper(num):
        if num == 1:
            return true
        return helper(get_next(num))

    return helper(n)
medium
A. Missing base case for cycle detection causing infinite recursion
B. Incorrect sum of squares calculation in get_next function
C. Returning helper(get_next(num)) without checking if num is 1
D. Not initializing total_sum to zero before summing digits

Solution

  1. Step 1: Analyze recursion base cases

    The code only stops recursion if num == 1. It does not detect cycles, so for unhappy numbers it recurses infinitely.
  2. Step 2: Identify missing cycle detection

    Without tracking visited numbers or using fast-slow pointers, the recursion never terminates for cycles, causing stack overflow.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Infinite recursion due to missing cycle detection base case [OK]
Hint: Check for cycle detection in recursion to avoid infinite loops [OK]
Common Mistakes:
  • Assuming recursion stops at cycles without explicit detection
3. What is the time and space complexity of the optimal single-pass two-pointer approach to find the middle node of a singly linked list with n nodes?
medium
A. Time: O(n), Space: O(1)
B. Time: O(n^2), Space: O(1)
C. Time: O(n), Space: O(n)
D. Time: O(log n), Space: O(1)

Solution

  1. Step 1: Identify time complexity

    Fast pointer moves two steps per iteration, slow moves one; total iterations proportional to n -> O(n) time.
  2. Step 2: Identify space complexity

    Only two pointers used, no extra data structures -> O(1) space.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Linear time and constant space for two-pointer traversal [OK]
Hint: Two pointers traverse list once, no extra storage [OK]
Common Mistakes:
  • Confusing space with O(n) due to recursion
  • Assuming nested loops cause O(n^2)
  • Thinking fast pointer halves complexity to O(log n)
4. What is the space complexity of the optimal palindrome linked list check that reverses the second half in-place?
medium
A. O(n) due to storing node values in an array
B. O(1) because reversal is done in-place without extra data structures
C. O(log n) due to recursion stack in reversal
D. O(n) due to recursion stack in reversal

Solution

  1. Step 1: Identify auxiliary space usage

    The algorithm reverses the second half in-place using pointers, no extra arrays or stacks.
  2. Step 2: Check for recursion stack

    The reversal is iterative, so no recursion stack space is used.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    In-place iterative reversal uses constant extra space [OK]
Hint: Iterative reversal uses O(1) space, recursion would add stack space [OK]
Common Mistakes:
  • Confusing iterative reversal with recursive reversal
  • Assuming array storage is needed for palindrome check
  • Forgetting recursion stack space in complexity
5. If the linked list nodes cannot be modified (no extra fields allowed) and you want to detect a cycle in O(1) space, which approach correctly adapts Floyd's cycle detection algorithm to also find the entry point of the cycle?
hard
A. Use a hash set to store nodes and find the first repeated node as the cycle start.
B. Modify node values temporarily to mark visited nodes and revert after detection.
C. After detecting the cycle, reset slow to head and move both pointers one step at a time until they meet; the meeting point is the cycle start.
D. Run the fast pointer twice as fast until it reaches the end, then backtrack to find the cycle start.

Solution

  1. Step 1: Detect cycle using fast and slow pointers

    When fast and slow meet, a cycle exists but the meeting point is not necessarily the cycle start.
  2. Step 2: Find cycle entry point

    Reset slow to head, then move slow and fast one step at a time; their meeting point is the cycle start node.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Standard Floyd's algorithm extension for cycle entry detection [OK]
Hint: Reset slow to head after detection to find cycle start [OK]
Common Mistakes:
  • Using extra memory when O(1) space required
  • Modifying node values disallowed
  • Incorrect pointer movement after detection
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard