MediumNo. 2145

Count the Hidden Sequences — LeetCode 2145 Python Solution

Pattern
Prefix Sum
Topics
Array, Prefix Sum
Reading time
2 min

The 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].

Example

Input
differences = [1,-3,4], lower = 1, upper = 6
Output
2
Explanation
The possible hidden sequences are:

Python solution

PythonSolution
class Solution:
    def numberOfArrays(self, differences: List[int], lower: int, upper: int) -> int:
        x = mi = mx = 0
        for d in differences:
            x += d
            mi = min(mi, x)
            mx = max(mx, x)
        return max(upper - lower - (mx - mi) + 1, 0)

Complexity

Time
O(n)where n is the length of the array differences
Space · auxiliary
O(1)

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 2145. Count the Hidden Sequences is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Prefix Sum.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2145. Count the Hidden Sequences?

LeetCode 2145. Count the Hidden Sequences is rated Medium on LeetCode.

What is the time complexity of LeetCode 2145. Count the Hidden Sequences?

The Python solution on this page runs in O(n), where n is the length of the array \textit{differences}.

What is the space complexity of LeetCode 2145. Count the Hidden Sequences?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 2145. Count the Hidden Sequences cover?

LeetCode 2145. Count the Hidden Sequences is tagged Array and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.