Count the Hidden Sequences - Problem

You are given a 0-indexed array of n integers differences, which describes the differences between each pair of consecutive integers of a hidden sequence of length (n + 1). More formally, call the hidden sequence hidden, then we have that differences[i] = hidden[i + 1] - hidden[i].

You are further given two integers lower and upper that describe the inclusive range of values [lower, upper] that the hidden sequence can contain.

For example, given differences = [1, -3, 4], lower = 1, upper = 6, the hidden sequence is a sequence of length 4 whose elements are in between 1 and 6 (inclusive).

  • [3, 4, 1, 5] and [4, 5, 2, 6] are possible hidden sequences.
  • [5, 6, 3, 7] is not possible since it contains an element greater than 6.
  • [1, 2, 3, 4] is not possible since the differences are not correct.

Return the number of possible hidden sequences there are. If there are no possible sequences, return 0.

Input & Output

Example 1 — Basic Case
$ Input: differences = [1,-3,4], lower = 1, upper = 6
Output: 2
💡 Note: Hidden sequences of length 4. Starting with 3: [3,4,1,5] ✓. Starting with 4: [4,5,2,6] ✓. Starting with 5: [5,6,3,7] ✗ (7 > 6). Valid sequences: 2
Example 2 — No Valid Sequences
$ Input: differences = [4,-7,2], lower = 3, upper = 6
Output: 0
💡 Note: Any sequence will go outside bounds. For example, start=3: [3,7,0,2] has 7>6 and 0<3. No valid starting position exists.
Example 3 — Single Valid Start
$ Input: differences = [1,-1,1], lower = 1, upper = 3
Output: 1
💡 Note: Only starting with 2 works: [2,3,2,3]. All values stay within [1,3]. Other starts go out of bounds.

Constraints

  • 1 ≤ differences.length ≤ 105
  • -105 ≤ differences[i] ≤ 105
  • -108 ≤ lower ≤ upper ≤ 108

Visualization

Tap to expand
Count Hidden Sequences: Find Valid Starting PositionsInput: differences = [1, -3, 4], lower = 1, upper = 6Start = 3[3, 4, 1, 5]All in [1,6] ✓Start = 4[4, 5, 2, 6]All in [1,6] ✓Start = 5[5, 6, 3, 7]7 > 6 ✗Start = 2[2, 3, 0, 4]0 < 1 ✗Sequence Generation: start + differences[0] + differences[1] + ...Valid Sequences FoundOnly starts 3 and 4 workOutput: 2Each starting position generates a unique sequence of length n+1
Understanding the Visualization
1
Input
Differences [1,-3,4] and bounds [1,6]
2
Process
Generate sequences for each starting position
3
Output
Count sequences that stay within bounds
Key Takeaway
🎯 Key Insight: Use prefix sums to efficiently determine the valid range of starting positions without simulating every sequence
Asked in
Google 15 Amazon 12 Microsoft 8
28.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen