DDSA Solutions

2145. Count the Hidden Sequences

Time: O(n)
Space: O(1)

Problem Overview

Count the Hidden Sequences (Unknown) asks you to solve a structured algorithmic task. This is a common Array / Prefix Sum pattern in coding interviews. Compute prefix sum of differences; answer = (upper - lower) - (max_prefix - min_prefix) + 1.

A full step-by-step explanation is being added. See the study guide for pattern-based practice.

Approach

Compute prefix sum of differences; answer = (upper - lower) - (max_prefix - min_prefix) + 1.

Related patterns: Array, Prefix Sum

2145.cs
C#
// Approach: Compute prefix sum of differences; answer = (upper - lower) - (max_prefix - min_prefix) + 1.
// Time: O(n) Space: O(1)

public class Solution
{
    public int NumberOfArrays(int[] differences, int lower, int upper)
    {
        long prefix = 0;
        long mn = 0; // Starts from 0.
        long mx = 0; // Starts from 0.

        foreach (var d in differences)
        {
            prefix += d;
            mn = Math.Min(mn, prefix);
            mx = Math.Max(mx, prefix);
        }

        return (int)Math.Max(0L, (upper - lower) - (mx - mn) + 1);
    }
}
Was this solution helpful?

Related Problems