Answers for "pair with difference k"

C++
2

two elements with difference K in c++

bool diffK(int A[], int N, int K) {
    sort(A, A+N);
    int i = 0, j = 0;
    while (i < N && j < N) {
        if (A[i] == A[j] + K) return true;
        else if (A[i] < A[j] + K) i++;
        else j++;
    }
    return false;
}
Posted by: Guest on July-01-2020
0

Pairs with Specific Difference

function findPairsWithGivenDifference(arr, k):
    # since we don't allow duplicates, no pair can satisfy x - 0 = y
    if k == 0:
        return []
        
    map = {}
    answer = []
    
    for (x in arr):
        map[x - k] = x
    
    for (y in arr):
        if y in map:
            answer.push([map[y], y]) 

    return answer
Posted by: Guest on May-01-2022

Browse Popular Code Answers by Language