Count Distinct Pairs having Difference Equal to K

package org.wesome.dsalgo;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

class PairsWithDifference {
    static int countPairsWithDifference(int arr[], int diff) {
        Set<Integer> set = new HashSet<>();
        Arrays.stream(arr).forEach(set::add);
        int count = 0;
        for (int i : arr) {
            if (set.contains(i - diff)) {
                System.out.println(i + " subtracted from " + (i - diff) + " will be " + diff);
                count++;
            }
        }
        return count;
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import static org.wesome.dsalgo.PairsWithDifference.countPairsWithDifference;

class PairsWithDifferenceTest {

    @Test
    void countPairsWithDifferenceTest() {
        int arr[] = {1, 5, 3, 4, 2};
        int difference = 3;
        Assertions.assertEquals(2, countPairsWithDifference(arr, difference));
    }
}
plugins {
    id 'java'
    id "io.freefair.lombok" version "6.4.1"
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}

test {
    useJUnitPlatform()
}

 

follow us on