Ctrl K

Two Separate Segments With a Given Sum

Medium
You are given an array of positive integers values and an integer goal. A segment is one or more consecutive elements of the array. Pick two segments that each sum to exactly goal and do not share any element. Among all such pairs, find the one with the smallest total length and return that length. If there are no two such segments, return -1.
Example 1
values=[4, 1, 3, 2, 2, 5], goal=4 → 3

The segments summing to 4 are [4], [1, 3] and [2, 2]. The shortest disjoint pair is [4] with [1, 3] (or with [2, 2]): 1 + 2 = 3.

Example 2
values=[6, 2, 4, 6], goal=6 → 2

There are three segments: [6], [2, 4] and [6]. Taking both 6s is best: 1 + 1 = 2.

Example 3
values=[1, 2, 3, 1], goal=5 → -1

Only [2, 3] sums to 5; there is no second segment, so the answer is -1.

Constraints
  • 1 ≤ len(values) ≤ 10⁵
  • 1 ≤ values[i] ≤ 1000
  • 1 ≤ goal ≤ 10⁸
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLongest Shared Run MediumWords Hidden in a Text MediumLongest Equal-Gap Chain MediumTrim the Ends to a Target MediumShuttle Driver Earnings Medium
loading Python…
Input
values=[4, 1, 3, 2, 2, 5], goal=4
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 87 tests on the server, hidden ones included.