|
| 1 | +package com.codejayant.arrays; |
| 2 | + |
| 3 | +import org.junit.Assert; |
| 4 | + |
| 5 | +import java.util.HashSet; |
| 6 | + |
| 7 | +/** |
| 8 | + * For a given two array of integer, find out if there are integers in each array whose sum is equal to a given value. |
| 9 | + * If yes, return true otherwise false. |
| 10 | + * |
| 11 | + * Example: |
| 12 | + * Input: [1, 2, 3], [10, 20, 30, 40], 42 (value) |
| 13 | + * Output: true |
| 14 | + * Explanation: 2 (from first array) + 40 (from second array) = 42 |
| 15 | + */ |
| 16 | +public class SumOfTwo { |
| 17 | + |
| 18 | + public static void main(String[] args) { |
| 19 | + Integer[] a = {1, 2, 3}; |
| 20 | + Integer[] b = {10, 20, 30, 40}; |
| 21 | + |
| 22 | + Assert.assertTrue(sumOfTwo(a, b, 42)); |
| 23 | + Assert.assertFalse(sumOfTwo(a, b, 45)); |
| 24 | + Assert.assertTrue(sumOfTwo(a, b, 43)); |
| 25 | + |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * Calculate compliment from first array, save in a HashSet and check if the element exists by comparing with second array elements. |
| 30 | + * <p> |
| 31 | + * Time Complexity: O(n) since there are two sequential loop execution |
| 32 | + * <p> |
| 33 | + * Space Complexity: O(n) since a new DS HashSet is introduced saving all complimentary elements from Array first |
| 34 | + * |
| 35 | + * @param a first input array |
| 36 | + * @param b second input array |
| 37 | + * @param value input sum value |
| 38 | + * @return true if some element in First Array + some element in Second Array = {@code array} |
| 39 | + */ |
| 40 | + private static boolean sumOfTwo(Integer[] a, Integer[] b, int value) { |
| 41 | +// HashSet<Integer> complimentA = Arrays.stream(a) |
| 42 | +// .map(integer -> value - integer) |
| 43 | +// .collect(Collectors.toCollection(HashSet::new)); |
| 44 | + |
| 45 | + HashSet<Integer> complimentA = new HashSet<>(); |
| 46 | + for (Integer integer : a) { |
| 47 | + complimentA.add(value - integer); |
| 48 | + } |
| 49 | + |
| 50 | + for (Integer integer : b) { |
| 51 | + if (complimentA.contains(integer)) { |
| 52 | + return true; |
| 53 | + } |
| 54 | + } |
| 55 | + return false; |
| 56 | + } |
| 57 | + |
| 58 | +} |
0 commit comments