/
Pairs - Hackerrank Solutions
89 lines (52 loc) · 1.09 KB
/
Pairs - Hackerrank Solutions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
The Problem is as Follows:
You will be given an array of integers and a target value. Determine the number of pairs of array elements that have a difference equal to a target value.
For example, given an array of [1, 2, 3, 4] and a target value of 1, we have three values meeting the condition: 2-1=1, 3-2=1 , 4-3=1
Pairs Hackerrank Solution Java:
-
static int pairs(int k, int[] arr) {
int count=0;
for(int i=0;i<arr.length-1;i++)
{
for(int j=i+1;j<arr.length;j++){
if(Math.abs(arr[i]-arr[j])==k)count++;
}
}
return count;
}
-
Method 2:
Pairs Hackerrank Solution Java:
-
static int pairs(int k, int[] arr) {
int count=0;
Arrays.sort(arr);
int i=0;
int j=1;
while(j<arr.length)
{
if(arr[j]-arr[i]>k)i++;
else if(arr[j]-arr[i]<k)j++;
else{count++;
j++;}
}
return count;
}
-
Method 2 Python
Pairs Hackerrank Solution Python:
-
def pairs(k, arr):
count=0
arr.sort()
i=0
j=1
while j<len(arr):
if arr[j]-arr[i]>k:
i+=1
elif arr[j]-arr[i]<k:
j+=1
else:
count+=1
j+=1
return count
-