Skip to content

Commit fc4e823

Browse files
committed
Solution to find swap number so that sum becomes equal
1 parent a38edee commit fc4e823

File tree

1 file changed

+79
-0
lines changed
  • src/main/java/com/eprogrammerz/examples/algorithm/crackingCoding

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
package com.eprogrammerz.examples.algorithm.crackingCoding;
2+
3+
import org.junit.Test;
4+
5+
import java.util.HashSet;
6+
import java.util.Set;
7+
8+
import static org.junit.Assert.assertArrayEquals;
9+
import static org.junit.Assert.assertEquals;
10+
11+
/**
12+
* Given two arrays of integers, find a pair of values (one value from each array) that you can swap to give the two arrays the same sum.
13+
*/
14+
public class SumSwap {
15+
/**
16+
* EXAMPLE
17+
* Input: {4, 1, 2, 1, 1, 2} and {3, 6, 3, 3}
18+
* Output: {1, 3}
19+
*
20+
* @param arr1
21+
* @param arr2
22+
* @return
23+
*/
24+
private int[] findSumSwapPair(int[] arr1, int[] arr2) {
25+
26+
/**
27+
* sumA - a + b = sumB - b + a
28+
* 2(a-b) = sumA-sumB
29+
* (a-b) = (sumA-sumB)/2
30+
*/
31+
Integer diff = getTarget(arr1, arr2);
32+
if (diff == null) return null;
33+
34+
Set<Integer> set2 = getHashSet(arr2);
35+
36+
for (int i = 0; i < arr1.length; i++) {
37+
int a = arr1[i];
38+
int b = diff + a;
39+
if (set2.contains(b)) {
40+
return new int[]{arr1[i], b};
41+
}
42+
}
43+
44+
return null;
45+
}
46+
47+
private Integer getTarget(int[] arr1, int[] arr2) {
48+
int sum1 = findSum(arr1);
49+
int sum2 = findSum(arr2);
50+
51+
int diff = Math.abs(sum1 - sum2);
52+
if (diff % 2 != 0) return null;
53+
return diff / 2;
54+
}
55+
56+
private Set<Integer> getHashSet(int[] arr) {
57+
Set<Integer> set = new HashSet<>();
58+
for (int n : arr) {
59+
set.add(n);
60+
}
61+
return set;
62+
}
63+
64+
private int findSum(int[] arr) {
65+
int sum = 0;
66+
for (int n : arr) {
67+
sum += n;
68+
}
69+
return sum;
70+
}
71+
72+
@Test
73+
public void testFindSumSwap() {
74+
int[] arr1 = new int[]{4, 1, 2, 1, 1, 2};
75+
int[] arr2 = new int[]{3, 6, 3, 3};
76+
int[] res = findSumSwapPair(arr1, arr2);
77+
assertArrayEquals(new int[]{4, 6}, res);
78+
}
79+
}

0 commit comments

Comments
 (0)