• + 0 comments

    Golang Time Complexity: O(n) Space Complexity: O(n)

    First: populates a hash map with all elements from the input array arr for quick lookups.

    Second: For each element x, it checks if x - k and x + k exist in the hash map. if exist, count

    The current element x is then removed from the hash map to prevent counting the same pair twice (e.g., counting (3, 5) when x=3 and then again when x=5)

    func pairs(k int32, arr []int32) int32 {
    exist := make(map[int32]bool)
    for _, x := range arr {
        exist[x] = true
    }
    
    count := int32(0)
    for _, x := range arr {
        if exist[x-k] {
            count++
        }
        if exist[x+k] {
            count++
        }
        exist[x] = false
    }
    return count
    

    }

    `