# https://www.hackerrank.com/challenges/minimum-absolute-difference-in-an-array/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=greedy-algorithms
import itertools

def min_absolute_diff5(arr):
    arr.sort()
    #initiate value using the first two element
    min_dif = abs(arr[0] - arr[1])
    #go over the sorted list and compare the distance between neighbors, once you sort thhe shortest distance neighbors will be next to each other
    for i in range(len(arr)-1):
        dif = abs(arr[i] - arr[i+1])
        if dif < min_dif:
            min_dif = dif
    return min_dif

############## scratch below

def find_min_absolute_diff(arr):
    res = set()
    for i in range(len(arr)):
        for j in range(i, len(arr)):
            x =abs((arr[i]-arr[j]))
            if x>0:
                res.add(x)
                print("res=", res)

    return min(res)

# print(find_min_absolute_diff([-2,2,4]))
# print(find_min_absolute_diff([3,-7,0]))


def find_min_absolute_diff2(arr):
    arr = list(set(arr))
    res = abs(arr[0]-arr[1])
    pairs = list(itertools.combinations(arr, 2))
    print("pairs=", pairs)
    for pair in pairs:
        x =abs((pair[0]-pair[1]))
        if x == 0:
            return 0
        if x < res:
            res =x

    return res

# print(find_min_absolute_diff2([-2,2,4]))
# print(find_min_absolute_diff2([3,-7,0]))

# needs to be faster 
def find_min_absolute_diff3(arr):
    seen=set()
    arr = list(set(arr))
    min_ = abs(arr[0]-arr[1])
    N=len(arr)
    for i in range(N):
        for j in range(i+1, N):
            if (arr[i], arr[j]) not in seen:
                x =  abs(arr[i]-arr[j])
                # diff[(arr[i], arr[j])] = x
                if x == 0:
                    return 0
                if x < min_:
                    min_ = x

    return min_

# print(find_min_absolute_diff3([-2,2,4]))
# print(find_min_absolute_diff3([3,-7,0]))


def find_min_absolute_diff4(arr):
    arr = list(set(arr))
    arr.sort()
    min_ = abs(arr[0]-arr[1])
    N=len(arr)-1

    i = 0
    j = 1
    while i < N:
        print("i=", i)
        print("j=",j)
        if j == N:
            i+=1
            j=i+1
        if j<=N:
            x =  abs(arr[i]-arr[j])
            if x < min_:
                if min_ == 0:
                    return 0
                min_ = x      
            j+=1
        else:
            break

    return min_

print(find_min_absolute_diff4([-2,2,4]))
print(find_min_absolute_diff4([3,-7,0]))


def min_absolute_diff5(arr):
    arr.sort()
    #initiate value using the first two element
    min_dif = abs(arr[0] - arr[1])
    #go over the sorted list and compare the distance between neighbors
    for i in range(len(arr)-1):
        dif = abs(arr[i] - arr[i+1])
        if dif < min_dif:
            min_dif = dif
    return min_dif


