Count the Hidden Sequences - Problem

Imagine you're a detective trying to reconstruct a hidden sequence of numbers based on clues about the differences between consecutive elements!

You are given:

  • An array differences of length n, where differences[i] = hidden[i + 1] - hidden[i]
  • Two integers lower and upper defining the valid range [lower, upper] for all elements in the hidden sequence

Your mission: Count how many different hidden sequences of length n + 1 are possible!

Example: Given differences = [1, -3, 4], lower = 1, upper = 6:

  • [3, 4, 1, 5] works (differences: 4-3=1, 1-4=-3, 5-1=4)
  • [4, 5, 2, 6] works (same differences pattern)
  • [5, 6, 3, 7] fails (7 > upper bound 6)

The key insight: once you pick the first number, the entire sequence is determined by the differences!

Input & Output

example_1.py — Basic Case
$ Input: differences = [1, -3, 4], lower = 1, upper = 6
Output: 2
💡 Note: Two valid hidden sequences exist: [3,4,1,5] and [4,5,2,6]. Both sequences have all elements within [1,6] and satisfy the difference constraints.
example_2.py — No Valid Sequences
$ Input: differences = [3, -4, 5, 1, -2], lower = -1, upper = 5
Output: 0
💡 Note: No matter what starting value we choose, at least one element in the resulting sequence will fall outside the range [-1, 5].
example_3.py — Large Range
$ Input: differences = [4, -7, 2], lower = 3, upper = 6
Output: 2
💡 Note: The valid sequences are [4,8,1,3] and [5,9,2,4]. Wait, that's wrong - let me recalculate: valid sequences are [6,10,3,5] - no, that exceeds upper bound. Actually, the answer should be calculated using the prefix sum method.

Constraints

  • 1 ≤ differences.length ≤ 105
  • -105 ≤ differences[i] ≤ 105
  • -108 ≤ lower ≤ upper ≤ 108
  • All elements in valid sequences must be in range [lower, upper]

Visualization

Tap to expand
🏔️ Mountain Hiking Trail AnalogyStart+1-3+4EndDANGER ZONE (below lower bound)DANGER ZONE (above upper bound)SAFE ZONE [lower, upper]💡 Key Insight: Find the lowest and highest points on your journey,then calculate which starting elevations keep you in the safe zone!
Understanding the Visualization
1
Map the Journey
Calculate cumulative elevation changes (prefix sums)
2
Find Extremes
Identify the lowest and highest points you'll reach
3
Safety Check
Determine which starting elevations keep you within safe bounds
4
Count Options
Calculate how many valid starting elevations exist
Key Takeaway
🎯 Key Insight: Use prefix sums to map the 'elevation profile' of your sequence journey, then mathematically determine the valid starting range instead of testing each possibility!
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
28.4K Views
Medium Frequency
~18 min Avg. Time
892 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