|
| 1 | +package algoDaily; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +/** |
| 6 | + * Given an array of numbers, return true if there is a subarray that sums up to a certain number n. |
| 7 | + * <p> |
| 8 | + * A subarray is a contiguous subset of the array. For example the subarray of [1,2,3,4,5] is [1,2,3] or [3,4,5] or [2,3,4] etc. |
| 9 | + * <p> |
| 10 | + * In the above examples, [2, 3] sum up to 5 so we return true. On the other hand, no subarray in [11, 21, 4] can sum up to 9. |
| 11 | + * <p> |
| 12 | + * Can you create a function subarraySum that accomplishes this? |
| 13 | + * <p> |
| 14 | + * Constraints |
| 15 | + * Length of the array <= 100000 |
| 16 | + * The values in the array will be between 0 and 1000000000 |
| 17 | + * The target sum n will be between 0 and 1000000000 |
| 18 | + * The array can be empty |
| 19 | + * Expected time complexity : O(n) |
| 20 | + * Expected space complexity : O(n) |
| 21 | + */ |
| 22 | +public class _21_ContiguousSubarraySum { |
| 23 | + |
| 24 | + // Time: O(n^2) | Space: O(1) |
| 25 | + public static boolean subArraySum(int[] array, int target) { |
| 26 | + for (int i = 0; i < array.length; i++) { |
| 27 | + int sum = 0; |
| 28 | + for (int j = 0; j < i; j++) { |
| 29 | + sum += array[j]; |
| 30 | + if (sum == target) return true; |
| 31 | + } |
| 32 | + } |
| 33 | + return false; |
| 34 | + } |
| 35 | + |
| 36 | + // Time: O(n) | Sum: O(1) |
| 37 | + public static boolean optimizedSubArraySum(int[] array, int target) { |
| 38 | + int curr_sum = array[0], start = 0, i; |
| 39 | + |
| 40 | + for (i = 1; i <= array.length; i++) { |
| 41 | + // If curr_sum exceeds the sum, |
| 42 | + // then remove the starting elements |
| 43 | + while (curr_sum > target && start < i - 1) { |
| 44 | + curr_sum -= array[start]; |
| 45 | + start++; |
| 46 | + } |
| 47 | + |
| 48 | + // If curr_sum becomes equal to sum, |
| 49 | + // then return true |
| 50 | + if (curr_sum == target) { |
| 51 | + int p = i - 1; |
| 52 | + System.out.println( "Sum found between indexes " + start + " and " + p); |
| 53 | + return true; |
| 54 | + } |
| 55 | + |
| 56 | + // Add this element to curr_sum |
| 57 | + if (i < array.length) |
| 58 | + curr_sum += array[i]; |
| 59 | + } |
| 60 | + |
| 61 | + System.out.println("No subarray found"); |
| 62 | + return false; |
| 63 | + |
| 64 | + } |
| 65 | + |
| 66 | + // Variation Problem: https://leetcode.com/problems/continuous-subarray-sum/ |
| 67 | + public static void main(String[] args) { |
| 68 | + System.out.println(optimizedSubArraySum(new int[]{1, 2, 3, 4, 5}, 21)); |
| 69 | + } |
| 70 | + |
| 71 | +} |
0 commit comments