Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Wednesday, June 28, 2017

Pairs Hackerrank solution in java


Problem :
count the number of pairs of integers whose difference is K.

Idea was to use two pointer algo which can do this task in O(n).

code:
import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
       
        Scanner ab=new Scanner(System.in);
        int n=ab.nextInt();
        int k=ab.nextInt();
        int count=0;
        long arr[]=new long[n];
        for(int i=0;i<n;i++)
            arr[i]=ab.nextLong();
        Arrays.sort(arr);
        int i=0,j=1;
   
    while(j < n) {
        long diff = arr[j] - arr[i];
       
        if (diff == k) {
            count++;
            j++;
        } else if (diff > k) {
            i++;
        } else if (diff < k) {
            j++;
        }
    }
        System.out.println(count);
    }
}

0 Comments:

Post a Comment

Stats