package cokr.xit.problems;

import org.junit.jupiter.api.Test;

public class FindDuplicateNumber {

    @Test
    public void main(){
        int[] nums = {1,3,4,2,2};
        System.out.println(String.format("{1,3,4,2,2} in duplicate number => %s", findDuplicate(nums)));

        nums = new int[]{3,1,3,4,2};
        System.out.println(String.format("{3,1,3,4,2} in duplicate number => %s", findDuplicate(nums)));

        nums = new int[]{1,1};
        System.out.println(String.format("{1,1} in duplicate number => %s", findDuplicate(nums)));

        nums = new int[]{1,1,2};
        System.out.println(String.format("{1,1,2} in duplicate number => %s", findDuplicate(nums)));

        nums = new int[]{4,1,2,3,4};
        System.out.println(String.format("{4,1,2,3,4} in duplicate number => %s", findDuplicate(nums)));

    }

    private int findDuplicate(int[] nums) {

        int slow = nums[0], fast = nums[nums[0]];
        while (slow != fast) {
            slow = nums[slow];
            fast = nums[nums[fast]];
        }


        int index = 0;
        while (slow != index) {
            index = nums[index];
            slow = nums[slow];
        }

        return index;
    }
}
