Skip to content

Commit a8a87e8

Browse files
committed
Solution to find Pairs Difference using Two Pointers Approach
1 parent 1f344b4 commit a8a87e8

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package Scaler.Assignments.TwoPointers;
2+
3+
public class PairsWithDifference {
4+
public static void main(String[] args) {
5+
6+
// int array [] = {-3,0,1,3,6,8,11,14,18,25};
7+
int array [] = {1, 5, 3, 4, 2};
8+
int array2 [] = {1,1};
9+
//1, 5, 3, 4, 2
10+
//8, 12, 16, 4, 0, 20
11+
//1, 1, 1, 2, 2
12+
13+
int count = countPairsWithDifference(array,3);
14+
int sumCount = countPairsWithSum(array2,2);
15+
16+
System.out.println("The count of pairs is " + count);
17+
System.out.println("The count of sum pairs is " + sumCount);
18+
}
19+
20+
static int countPairsWithDifference(int [] A,int K){
21+
22+
int i = 0; int j = 1; int count = 0;
23+
24+
while (j < A.length){
25+
if (A[j]-A[i] == K && i!=j){
26+
count ++;
27+
j++;
28+
} else if (A[j]-A[i] > K && i!=j) {
29+
i++;
30+
}else {
31+
j++;
32+
}
33+
}
34+
return count;
35+
}
36+
37+
static int countPairsWithSum(int [] A,int K){
38+
39+
int i = 0; int j = A.length-1; int count = 0;
40+
41+
int height = Math.min(A[i],A[j]);
42+
43+
while (i < j){
44+
if (A[i]+A[j] == K){
45+
count ++;
46+
// i++;
47+
} else if (A[i]+A[i] > K) {
48+
j--;
49+
}else {
50+
i++;
51+
}
52+
}
53+
return count;
54+
}
55+
}

0 commit comments

Comments
 (0)