Skip to content

Commit b7f6535

Browse files
Equal sum subarrays in O(N) time (#193)
1 parent cdd745e commit b7f6535

File tree

2 files changed

+11
-10
lines changed

2 files changed

+11
-10
lines changed

array/equal_sum_subarrays.go

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
package array
22

3-
// EqualSubArrays solves the problem in O(n^2) time and O(1) space.
3+
// EqualSubArrays solves the problem in O(n) time and O(1) space.
44
func EqualSubArrays(list []int) [][]int {
55
output := make([][]int, 0)
66
if len(list) < 2 {
@@ -19,14 +19,15 @@ func EqualSubArrays(list []int) [][]int {
1919
}
2020

2121
func findSplitPoint(list []int) int {
22-
lSum := 0
23-
for i := range len(list) {
24-
lSum += list[i]
22+
lSum, rSum := 0, 0
2523

26-
rSum := 0
27-
for j := i + 1; j < len(list); j++ {
28-
rSum += list[j]
29-
}
24+
for _, n := range list {
25+
rSum += n
26+
}
27+
28+
for i, n := range list {
29+
lSum += n
30+
rSum -= n
3031

3132
if lSum == rSum {
3233
return i + 1

array/equal_sum_subarrays_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ TestEqualSumSubArrays tests solution(s) with the following signature and problem
1010
1111
func EqualSubArrays(list []int) [][]int
1212
13-
Given an list of integers A, return two sub-arrays with equal sums without changing the
14-
order of the elements in the list.
13+
Given an list of integers A, return two sub-arrays with equal sums that are a partition of the
14+
original list, without changing the order of the elements in the list.
1515
1616
For example given {1,7,3,5}, return {1,7} and {3,5} because 1+7 = 3+5 = 8.
1717
*/

0 commit comments

Comments
 (0)