Problem 1477

Abstract / Summary

Find two separate parts of an array that each add up to a given number and do not overlap.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1477.py

class Solution:
    def minSumOfLengths(self, arr: List[int], target: int) -> int:
        result = +inf

        prefix = [ 0 ] # prefix sum
        have   = []    # list of [ start, end ] for each subarray with sum == target
        for i, a in enumerate(arr):
            prefix.append(prefix[-1] + a)

            need = prefix[-1] - target
            pos  = bisect_left(prefix, need)
            # does it match the target sum ?
            if prefix[pos] == need:
                have.append(( pos, i ))

        # shortest subarray, beginning at pos
        size   = len(have)
        second = [ 0 ] * size + [ +inf ]
        for i in reversed(range(size)):
            a, b   = have[i]
            length = b - a + 1
            second[i] = min(second[i + 1], length)

        for i, (a, b) in enumerate(have):
            length = b - a + 1

            # skip if first part is already too long
            if length + 1 >= result:
                continue

            # earliest index of next match
            next = bisect_left(have, (b + 1, 0))
            if next == len(have): # no more matches
                break

            length += second[next]
            result  = min(result, length)

        return result if result != +inf else -1
39 lines | 1300 bytes | submitted May 3, 2024 | GitHub   25% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 37% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
  • Dynamic Programming
  • Hash Table
  • Sliding Window
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The implementation solves the problem of finding two non-overlapping sub-arrays whose sums equal a given target and whose total length is minimal. It builds a prefix-sum array to enable constant-time range-sum queries, then uses binary search to locate candidate sub-arrays. A second pass computes the minimal length of any qualifying sub-array that starts at or after each candidate, allowing the final combination step to evaluate pairs efficiently.

Prefix construction and candidate detection

The algorithm begins by initializing a prefix-sum list with a zero sentinel. As it iterates through the input arr, it appends the cumulative sum to prefix. For each new cumulative sum, the required previous sum (need) that would make a sub-array ending at the current index sum to target is computed. A binary search (bisect_left) on the sorted prefix list finds the earliest position where need could appear. If the value at that position matches need, a matching sub-array has been found and its start and end indices are stored in have.

prefix = [0]
have   = []
for i, a in enumerate(arr):
    prefix.append(prefix[-1] + a)

    need = prefix[-1] - target
    pos  = bisect_left(prefix, need)
    if prefix[pos] == need:
        have.append((pos, i))

Because prefix is built in order, it remains sorted, guaranteeing that bisect_left works correctly. This step captures every sub-array whose sum equals target while preserving their natural order.

Pre-computing the minimal suffix length

After all candidates are collected, the code prepares an auxiliary array second. Traversing have in reverse, it records at each index the smallest length among all sub-arrays starting at that index or later. This enables O(1) lookup of the best possible second sub-array when evaluating a pair.

size   = len(have)
second = [0] * size + [inf]
for i in reversed(range(size)):
    a, b   = have[i]
    length = b - a + 1
    second[i] = min(second[i + 1], length)

The extra sentinel inf at the end simplifies boundary handling, ensuring that second[i + 1] is always defined.

Pair evaluation and result determination

The main loop iterates over each candidate sub-array. It first discards any candidate whose length already exceeds the best known result (result). For the remaining candidates, a binary search finds the first subsequent candidate that starts after the current sub-array ends (b + 1). If such a candidate exists, the pre-computed minimal suffix length (second[next]) is added to the current length, and result is updated with the smaller total.

result = inf
for i, (a, b) in enumerate(have):
    length = b - a + 1

    if length + 1 >= result:
        continue

    next = bisect_left(have, (b + 1, 0))
    if next == len(have):
        break

    length += second[next]
    result = min(result, length)

The early-exit condition if next == len(have): break stops the loop once no further non-overlapping partner can be found, avoiding unnecessary iterations.

Finally, the function returns the computed minimal total length, or -1 if no valid pair exists.

return result if result != inf else -1

Edge-case handling

The algorithm gracefully handles an empty input array: the prefix list contains only the sentinel zero, the loop never adds entries to have, and the final return yields -1. When no sub-array sums to target, have remains empty, causing the result to stay at inf and the function to return -1. Overlapping sub-arrays are automatically excluded because the binary search for the second sub-array requires its start index to be greater than the end index of the first (b + 1). The sentinel inf in second ensures that attempts to access beyond the last candidate do not cause index errors. The use of bisect_left on a sorted prefix list guarantees correct detection even when duplicate prefix sums appear, as the earliest matching position is selected.

Performance optimizations

The prefix-sum approach reduces the sub-array sum check to a constant-time arithmetic operation, eliminating the need for nested loops. Binary search (bisect_left) on the monotonic prefix array provides O(log n) lookup for each candidate, keeping the candidate detection phase efficient. Storing candidates in have preserves order, allowing a second binary search to locate the next non-overlapping candidate quickly. The reverse traversal that builds second computes minimal suffix lengths in a single pass, avoiding repeated scans during pair evaluation. Early termination checks (if length + 1 >= result and if next == len(have): break) prune the search space, preventing unnecessary work once a sufficiently good result is found or when no further pairs are possible. The overall design leverages sorted structures and pre-computed minima to achieve a streamlined, low-overhead solution.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long row of numbered blocks laid out on the floor. Each block has a different number written on it. Finding a specific target sum is like trying to find two separate small sections of these blocks that each add up to the same number, but make sure they do not overlap.

First, the code walks through the row of blocks one by one. It keeps track of the running total of the numbers it has seen so far. By looking back at these totals, it can spot exactly where a group of blocks adds up to the goal. It makes a list of all these groups and remembers where each one starts and ends.

Once it has a list of every group that reaches the goal, it needs to find the two shortest ones that do not bump into each other. It looks at the list of matches and saves the shortest length it found while reading from the end to the start. This helps when comparing the groups later. Finally, it checks pairs of groups to see if they fit together without overlapping. It keeps track of the smallest combined size of any two groups that it can find, effectively searching through all the possibilities to see which two sections are the tiniest.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6 | μ = 5.92 | σ = 1.66

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Java
leetcode.ca C++ Python Java Go TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
FelixFan1122 C#
fsq C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
suxrobGM C#
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
FelixFan1122 C#
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
suxrobGM C#
23 links | 13 authors | 7 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

11 solutions   May 3, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality