Skip to content

Commit 0936993

Browse files
committed
1. Solution to search for an Element in an Array
2. Solution to find the Good Pair in an ArrayList
1 parent 0e677d1 commit 0936993

2 files changed

Lines changed: 102 additions & 1 deletion

File tree

‎src/Arrays/GoodPair.java‎

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
package Arrays;
2+
3+
import java.util.ArrayList;
4+
5+
/*
6+
* Given an array A and an integer B. A pair(i, j) in the array is a good pair if i != j and (A[i] + A[j] == B).
7+
* Check if any good pair exist or not.
8+
*
9+
* Problem Constraints
10+
11+
1 <= A.size() <= 104
12+
13+
1 <= A[i] <= 109
14+
15+
1 <= B <= 109
16+
17+
* * Input Format
18+
19+
First argument is an integer array A.
20+
21+
Second argument is an integer B.
22+
23+
* Output Format
24+
25+
Return 1 if good pair exist otherwise return 0.
26+
*
27+
* Example Input
28+
29+
Input 1:
30+
31+
A = [1,2,3,4]
32+
B = 7
33+
Input 2:
34+
35+
A = [1,2,4]
36+
B = 4
37+
Input 3:
38+
39+
A = [1,2,2]
40+
B = 4
41+
42+
43+
Example Output
44+
45+
Output 1:
46+
1
47+
*
48+
Output 2:
49+
0
50+
*
51+
Output 3:
52+
1
53+
54+
Example Explanation
55+
56+
Explanation 1:
57+
58+
(i,j) = (3,4)
59+
Explanation 2:
60+
61+
No pair has sum equal to 4.
62+
Explanation 3:
63+
64+
(i,j) = (2,3)
65+
* */
66+
public class GoodPair {
67+
public static void main(String[] args) {
68+
69+
ArrayList<Integer> list_1 = new ArrayList<>(10);
70+
list_1.add(1);
71+
list_1.add(2);
72+
list_1.add(3);
73+
list_1.add(4);
74+
75+
System.out.println(solve(list_1,7));
76+
}
77+
78+
static int solve(ArrayList<Integer> A, int B) {
79+
80+
int isGoodPair = 0;
81+
82+
for (int i = 0;i < A.size();i++){
83+
84+
int element = A.get(i);
85+
86+
for (int j = i+1; j <= A.size()-1; j++){
87+
88+
// System.out.println(i + " " + j);
89+
if (A.get(i)+A.get(j) == B){
90+
isGoodPair = 1;
91+
break;
92+
}
93+
}
94+
if (isGoodPair == 1){
95+
break;
96+
}
97+
}
98+
99+
return isGoodPair;
100+
}
101+
}

‎src/Scaler/Assignments/SearchElement.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ public static void main(String[] args) {
2121
array[k] = scanner.nextInt();
2222
}
2323

24-
System.out.println(array);
24+
// System.out.println(array);
2525

2626
int searchNumber = scanner.nextInt();
2727

0 commit comments

Comments
 (0)