|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +/** |
| 4 | + * 457. Circular Array Loop |
| 5 | + * |
| 6 | + * You are given an array of positive and negative integers. |
| 7 | + * If a number n at an index is positive, then move forward n steps. |
| 8 | + * Conversely, if it's negative (-n), move backward n steps. |
| 9 | + * |
| 10 | + * Assume the first element of the array is forward next to the last element, |
| 11 | + * and the last element is backward next to the first element. |
| 12 | + * Determine if there is a loop in this array. |
| 13 | + * A loop starts and ends at a particular index with more than 1 element along the loop. The loop must be "forward" or "backward'. |
| 14 | + * |
| 15 | + * Example 1: Given the array [2, -1, 1, 2, 2], there is a loop, from index 0 -> 2 -> 3 -> 0. |
| 16 | + * Example 2: Given the array [-1, 2], there is no loop. |
| 17 | + * |
| 18 | + * Note: The given array is guaranteed to contain no element "0". |
| 19 | + * |
| 20 | + * Can you do it in O(n) time complexity and O(1) space complexity? |
| 21 | + */ |
| 22 | +public class _457 { |
| 23 | + public static class Solution1 { |
| 24 | + /** |
| 25 | + * credit: https://discuss.leetcode.com/topic/66894/java-slow-fast-pointer-solution |
| 26 | + */ |
| 27 | + public boolean circularArrayLoop(int[] nums) { |
| 28 | + int n = nums.length; |
| 29 | + for (int i = 0; i < n; i++) { |
| 30 | + if (nums[i] == 0) { |
| 31 | + continue; |
| 32 | + } |
| 33 | + // slow/fast pointer |
| 34 | + int j = i, k = getIndex(i, nums); |
| 35 | + while (nums[k] * nums[i] > 0 && nums[getIndex(k, nums)] * nums[i] > 0) { |
| 36 | + if (j == k) { |
| 37 | + // check for loop with only one element |
| 38 | + if (j == getIndex(j, nums)) { |
| 39 | + break; |
| 40 | + } |
| 41 | + return true; |
| 42 | + } |
| 43 | + j = getIndex(j, nums); |
| 44 | + k = getIndex(getIndex(k, nums), nums); |
| 45 | + } |
| 46 | + // loop not found, set all element along the way to 0 |
| 47 | + j = i; |
| 48 | + int val = nums[i]; |
| 49 | + while (nums[j] * val > 0) { |
| 50 | + int next = getIndex(j, nums); |
| 51 | + nums[j] = 0; |
| 52 | + j = next; |
| 53 | + } |
| 54 | + } |
| 55 | + return false; |
| 56 | + } |
| 57 | + |
| 58 | + public int getIndex(int i, int[] nums) { |
| 59 | + int n = nums.length; |
| 60 | + return i + nums[i] >= 0 ? (i + nums[i]) % n : n + ((i + nums[i]) % n); |
| 61 | + } |
| 62 | + } |
| 63 | +} |
0 commit comments