- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 39 lines of Java from the credited upstream file 457.java.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public boolean circularArrayLoop(int[] nums) {3 if (nums.length < 2)4 return false;5 6 for (int i = 0; i < nums.length; ++i) {7 if (nums[i] == 0)8 continue;9 int slow = i;10 int fast = advance(nums, slow);11 while (nums[i] * nums[fast] > 0 && nums[i] * nums[advance(nums, fast)] > 0) {12 if (slow == fast) {13 if (slow == advance(nums, slow))14 break;15 return true;16 }17 slow = advance(nums, slow);18 fast = advance(nums, advance(nums, fast));19 }20 21 slow = i;22 final int sign = nums[i];23 while (sign * nums[slow] > 0) {24 final int next = advance(nums, slow);25 nums[slow] = 0;26 slow = next;27 }28 }29 30 return false;31 }32 33 private int advance(int[] nums, int i) {34 final int n = nums.length;35 final int val = (i + nums[i]) % n;36 return i + nums[i] >= 0 ? val : n + val;37 }38}39