0% found this document useful (0 votes)
86 views

Subarray Sum

The document discusses three techniques - Kadane's algorithm, sliding window, and cumulative sums - to solve subarray problems in linear time and constant or linear space. It provides detailed explanations of the solutions along with pseudocode and time/space complexity analyses.

Uploaded by

abhi74
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views

Subarray Sum

The document discusses three techniques - Kadane's algorithm, sliding window, and cumulative sums - to solve subarray problems in linear time and constant or linear space. It provides detailed explanations of the solutions along with pseudocode and time/space complexity analyses.

Uploaded by

abhi74
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

 

Interview Camp 

 
Technique #1: Kadane's Algorithm 

Level: Medium 

Given an array of integers that can be both +ve and -ve, find the contiguous subarray 
with the largest sum.  
e.g, [1,2,-1,2,-3,2,-5] -> the first 4 elements have the largest sum. 
 
Questions to Clarify: 
Q. How do you want the output? 
A. Return the value of the maximum sum. 
 
Q. Do empty arrays count as a subarray? 
A. Yes 

Solution: 
The brute force solution is to iterate through each subarray by using two for loops, and  
calculating the sum of each subarray. 
 
for i -> 0 to a.length 
sum = 0 
for j -> i to a.length 
sum = sum + a[j] 
check if sum is max and save if so 
 
This takes O(n^2) time and O(1) space. It is good to mention this to the interviewer. 
We can however, do this problem in O(n) time and O(1) space. 
 
We use Kadane's algorithm. If we know the max sum ending at a[i-1], 
we can calculate the max sum ending at a[i]. 
 
max_sum_ending_at[i] = Max(max_sum_ending_at[i-1] + a[i], 0) 
 
This is because if a sum ending at i is -ve, then 0 is always  
the better sum, because the sum of an empty subarray is always zero. 

Pseudocode: 
for i -> 0 to a.length - 1:
find max sum ending at i
if largest sum encountered so far:
save in a variable

Test Cases: 
Edge Cases: empty array, null array 
Base Cases: single element (+ve, 0, -ve), two elements 
Regular Cases: all -ve, all +ve, mix -ve and +ve, all 0s 

 
 
© ​2015-2019 Interview Camp (interviewcamp.io) 
 
Interview Camp 

Time Complexity: O(n) 

Space Complexity: O(1) 


 
public static Integer maximumSumSubarray(int[] a) {
if (a == null)
return 0;

int maxSum = 0, maxEndingHere = 0;

for (int i = 0; i < a.length; i++) {


maxEndingHere = Math.max(maxEndingHere + a[i], 0);
maxSum = Math.max(maxSum, maxEndingHere);
}

return maxSum;
}
 
   

 
 
© ​2015-2019 Interview Camp (interviewcamp.io) 
 
Interview Camp 

Technique #2: Sliding Window 

Level: Medium 

Given an array of positive integers, find a subarray that sums to a given number X. 
 
Questions to Clarify: 
Q. How to return the input? 
A. Return that start and end indices of the subarray. 
 
Q. What to return if the array is empty or null? 
A. Return null. 
 
Q. What to return if no subarray is found? 
A. Return null. 
 
Q. What to do if there are multiple subarrays? 
A. Return any one. 

Solution: 
The brute force algorithm (going through each subarray) takes O(n^2) time and O(1) space. 
We can solve this problem with O(n) time and O(1) space. 
 
We use the technique of using a sliding window and shifting it forward. 
We keep a two pointers, i and j. They both start with 0. We keep track of the sum of subarray [i,j]. 
If the sum is less than X, we advance j by 1 and add a[j] to the sum. If sum is greater than X, 
we advance i by 1 and subtract a[i] from the sum. Keep in mind i is always behind j. 

Pseudocode: 
i=0,j=0,sum = a[0]
while both i and j are within the array
if (sum > X)
move i forward and reduce sum by a[i]
else if (sum < X)
move j forward, increase sum by a[j+1]
else return [i,j]

Test Cases: 
Edge Cases: empty array, null array 
Base Cases: single element (more/less/equal to X) 
Regular Cases: two elements, no sum equals to X, etc. 

Time Complexity: O(n) 

Space Complexity: O(1) 


Follow Up: 
What if there can be negative integers in the array? 

 
 
© ​2015-2019 Interview Camp (interviewcamp.io) 
 
Interview Camp 

 
public static Pair<Integer> xSumSubarray(int[] a, int x) {
if (a == null || a.length == 0)
return null;

int i = 0, j = 0, sum = a[0];


while (i < a.length) {
if (i > j) { // i inched forward, bring j back to i
j = i;
sum = a[i];
} else if (sum > x) {
sum = sum - a[i++];
} else if (sum < x) {
if ((j+1) < a.length)
sum = sum + a[++j];
else
break; // reached end, cannot expand further
} else {
return new Pair<Integer>(i,j);
}
}

return null;
}
 
   

 
 
© ​2015-2019 Interview Camp (interviewcamp.io) 
 
Interview Camp 

Technique #3: Cumulative Sums 

Level: Medium 

Given an array of integers, both -ve and +ve, find a contiguous subarray that sums to 0. 
 
For example: [2,4,-2,1,-3,5,-3] --> [4,-2,1,-3] 
 
Questions to Clarify: 
Q. What form to return the input? 
A. Return the starting and ending indices of the subarray. 
 
Q. What to return if the array is empty or null? 
A. Return null. 
 
Q. What to return if no subarray is found? 
A. Return null. 
 
Q. What to do if there are multiple subarrays? 
A. Return any one. 

Solution: 
The brute force algorithm (going through each subarray) takes O(n^2) time and O(1) space. 
We can solve this problem with O(n) time and O(n) space. This may or may not be better, 
depending on how much space the interviewer wants to use. So it is good to clarify. 
 
We use the technique of cumulative sums. For all elements, we first calculate the sum s[i] which 
is the sum of all numbers from a[0] to a[i]. An interesting property emerges: If any s[i] is 0,  
then a[0] to a[i] sums to 0, so [0,i] is the answer. If there is no s[i] that sums to zero, we  
try to find two s[i]'s that have the same value. If s[j] and s[k] have the same value, then the  
sum of subarray [j+1,k] is 0. 
 
Example: 
A = [2,4,-2,1,-3,5,-3] 
Generate Cumulative Sum Array => [2,6,4,5,2,7,4] 
We see that there are 2 sub arrays with sum 0 -> a[1..4] and a[3..6] 
 
Homework: This technique can also be used to find a subarray that sums to any X instead of 0. 

Pseudocode: 
At each index i, keep track of cumulative sum. If we encounter sum 0 at i,
return (0,i) as answer.
We also keep a map of old sums. If we find a sum again, we return that
subarray.

sum = 0
hashmap map = {}

 
 
© ​2015-2019 Interview Camp (interviewcamp.io) 
 
Interview Camp 

for i -> 0 to a.length - 1:


sum = sum + a[i]

if sum == 0:
return (0,i)

if map already has sum:


return (map.get(sum)+1, i)

add (sum, i) to map

if noting found, return null

Test Cases: 
Edge Cases: Empty Array, Null array 
Base Cases: single element (-ve, +ve, 0) 
Regular Cases: has sum, does not have sum, has sum at beginning/end/middle 

Time Complexity: O(n) 

Space Complexity: O(n) 


 
public static Pair<Integer> zeroSumSubarray(int[] a) {
if (a == null || a.length == 0)
return null;

int sum = 0;
HashMap<Integer, Integer> map = new HashMap<>();

for (int i = 0; i < a.length; i++) {


sum += a[i];

if (sum == 0) {
return new Pair<Integer>(0,i);
}

if (map.containsKey(sum)) {
return new Pair<Integer>(map.get(sum)+1, i);
}

map.put(sum, i);
}

return null; // not found


}
 

 
 
© ​2015-2019 Interview Camp (interviewcamp.io) 

You might also like