BackmediumSliding Windowuncategorizedmedium

Smart Traffic Flow Optimization Solution

Problem Statement

A metropolitan traffic control system manages a linear sequence of N intersections, each equipped with a smart signal controller. The system receives a stream of traffic density readings for each intersection, represented as an array traffic. To optimize flow, the central algorithm must identify the longest contiguous segment of intersections where the cumulative traffic density remains strictly below a critical threshold K. If multiple segments of the same maximum length exist, return the one that starts at the earliest index. If no such segment exists (i.e., every single intersection exceeds or equals the threshold), return -1.

The input consists of an integer array traffic of length N, where each element represents the current density level at that intersection, and an integer K representing the maximum allowable cumulative density for a stable flow segment. The output is the length of the longest valid contiguous subarray where the sum of elements is strictly less than K.

This problem requires an efficient sliding window approach to handle large input sizes within time limits. The solution must process the array in linear time, adjusting the window boundaries dynamically to maintain the sum constraint.

Example 1
Input
traffic = [2, 4, 1, 3, 5], K = 10
Output
3

Explanation: We examine contiguous subarrays: - [2]: sum=2 < 10 (len 1) - [2,4]: sum=6 < 10 (len 2) - [2,4,1]: sum=7 < 10 (len 3) - [2,4,1,3]: sum=10 is NOT < 10 (invalid) - [4,1]: sum=5 < 10 (len 2) - [4,1,3]: sum=8 < 10 (len 3) - [4,1,3,5]: sum=13 >= 10 (invalid) - [1,3]: sum=4 < 10 (len 2) - [1,3,5]: sum=9 < 10 (len 3) - [3,5]: sum=8 < 10 (len 2) - [5]: sum=5 < 10 (len 1) The maximum length found is 3.

Example 2
Input
traffic = [10, 10, 10], K = 5
Output
-1

Explanation: Every single element is 10, which is >= 5. Therefore, no contiguous subarray (even of length 1) has a sum strictly less than 5. The result is -1.

Example 3
Input
traffic = [1, 2, 3, 4, 5, 6], K = 15
Output
4

Explanation: Check subarrays: - [1,2,3,4]: sum=10 < 15 (len 4) - [1,2,3,4,5]: sum=15 is NOT < 15 (invalid) - [2,3,4,5]: sum=14 < 15 (len 4) - [2,3,4,5,6]: sum=20 >= 15 (invalid) - [3,4,5]: sum=12 < 15 (len 3) - [4,5,6]: sum=15 is NOT < 15 (invalid) - [5,6]: sum=11 < 15 (len 2) The maximum length is 4.

Example 4
Input
traffic = [0, 0, 0, 0], K = 1
Output
4

Explanation: All elements are 0. The sum of the entire array is 0, which is strictly less than 1. The length of the entire array is 4. This is the maximum possible length.

Constraints

  • 1 <= traffic.length <= 10^5
  • 0 <= traffic[i] <= 10^4
  • 1 <= K <= 10^9
  • The sum of all elements in traffic may exceed 32-bit integer range, so use 64-bit integers for accumulation.
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Smart Traffic Flow Optimization — Problem Statement & Solution Guide

Sliding WindowMediumMixed
TimeO(N)
|
SpaceO(1)

Problem Description

A metropolitan traffic control system manages a linear sequence of N intersections, each equipped with a smart signal controller. The system receives a stream of traffic density readings for each intersection, represented as an array traffic. To optimize flow, the central algorithm must identify the longest contiguous segment of intersections where the cumulative traffic density remains strictly below a critical threshold K. If multiple segments of the same maximum length exist, return the one that starts at the earliest index. If no such segment exists (i.e., every single intersection exceeds or equals the threshold), return -1.

The input consists of an integer array traffic of length N, where each element represents the current density level at that intersection, and an integer K representing the maximum allowable cumulative density for a stable flow segment. The output is the length of the longest valid contiguous subarray where the sum of elements is strictly less than K.

This problem requires an efficient sliding window approach to handle large input sizes within time limits. The solution must process the array in linear time, adjusting the window boundaries dynamically to maintain the sum constraint.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Smart Traffic Flow Optimization"

medium

WHY DOES IT MATTER?

The sliding‑window pattern reduces quadratic time to linear by exploiting monotonic constraints, which is essential for real‑time traffic control systems that must process millions of readings per second. It also keeps memory usage minimal, a critical factor in embedded or edge devices.

OPTIMIZATION CHALLENGE

The core insight is that the constraint is monotonic: once the cumulative density exceeds the threshold, any larger window starting at the same left index will also exceed it. This allows us to discard entire ranges of subarrays in constant time, eliminating the need for nested loops.

REAL-WORLD CONNECTION

Think of a traffic controller that continuously monitors a stretch of road. As cars enter the segment, the controller keeps a running total of density. If the density exceeds a safety limit, it immediately signals the next intersection to slow down, effectively moving the left boundary of the monitored segment. This mirrors the algorithm’s left/right pointer movement.

When explaining this in an interview, highlight the invariant that the current window always satisfies the constraint, and that the left pointer only moves forward. This guarantees O(N) time and helps the interviewer see the algorithm’s correctness.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
💾 Space:O(1)

Core Theory — Why This Approach?

The problem of finding the longest contiguous segment whose cumulative traffic density stays below a given threshold is a classic example of the "maximum subarray with bounded sum" problem. A naive approach would examine every possible subarray, computing its sum and checking the constraint, leading to an O(N^2) time complexity that quickly becomes infeasible for large N. The optimal solution leverages the fact that all traffic densities are non‑negative (or at least the constraint is monotonic with respect to adding elements), allowing a two‑pointer or sliding‑window technique. By maintaining a window [left,right] and its current sum, we can expand the right pointer to include new intersections while the sum remains below the threshold. If the sum exceeds the limit, we increment the left pointer to shrink the window until the constraint is satisfied again. This linear‑time approach guarantees that each intersection is processed at most twice, yielding O(N) time and O(1) additional space.

The key insight is that the constraint is *monotonic*: adding more intersections can only increase the cumulative density. Therefore, once a window violates the threshold, any larger window starting at the same left index will also violate it, and we can safely move the left boundary forward. This property eliminates the need for nested loops and transforms the problem into a simple pointer‑movement exercise. The sliding‑window paradigm is widely applicable to problems involving contiguous subarrays with sum, product, or other aggregate constraints, making it a fundamental tool in a software engineer’s toolkit.

Interview Questions on This Problem

Q1How would you modify the sliding window algorithm if the traffic densities could be negative?

With negative values the monotonicity property breaks down, so a simple sliding window no longer guarantees correctness. In that case you would need to use a prefix sum array and a data structure like a balanced BST or a monotonic queue to keep track of the smallest prefix sum seen so far. For each right index you would query the earliest left index such that prefix[right]-prefix[left-1] <= threshold, which can be done in O(log N) per step, leading to O(N log N) overall.

Q2A fintech platform needs to detect the longest period of low transaction volume. The volume array can contain zeros. What edge cases should you consider?

Zeros do not affect the sum, so the window can be extended over them without violating the threshold. However, you must ensure that the algorithm correctly handles the case where the entire array sums to less than or equal to the threshold, returning N. Also, be careful with integer overflow when summing large values; use 64‑bit integers.

Q3During a coding interview, you are asked to explain why the two‑pointer approach works for this problem. What key property of the input do you emphasize?

I emphasize that the traffic densities are non‑negative (or that the constraint is monotonic with respect to adding elements). This guarantees that if a window [l,r] violates the threshold, any extension to the right will also violate it, so we can safely move the left pointer forward. This monotonicity is what allows the linear‑time sliding window to be correct.

Examples

Example 1

Input

traffic = [2, 4, 1, 3, 5], K = 10

Output

3

Explanation: We examine contiguous subarrays: - [2]: sum=2 < 10 (len 1) - [2,4]: sum=6 < 10 (len 2) - [2,4,1]: sum=7 < 10 (len 3) - [2,4,1,3]: sum=10 is NOT < 10 (invalid) - [4,1]: sum=5 < 10 (len 2) - [4,1,3]: sum=8 < 10 (len 3) - [4,1,3,5]: sum=13 >= 10 (invalid) - [1,3]: sum=4 < 10 (len 2) - [1,3,5]: sum=9 < 10 (len 3) - [3,5]: sum=8 < 10 (len 2) - [5]: sum=5 < 10 (len 1) The maximum length found is 3.

Example 2

Input

traffic = [10, 10, 10], K = 5

Output

-1

Explanation: Every single element is 10, which is >= 5. Therefore, no contiguous subarray (even of length 1) has a sum strictly less than 5. The result is -1.

Example 3

Input

traffic = [1, 2, 3, 4, 5, 6], K = 15

Output

4

Explanation: Check subarrays: - [1,2,3,4]: sum=10 < 15 (len 4) - [1,2,3,4,5]: sum=15 is NOT < 15 (invalid) - [2,3,4,5]: sum=14 < 15 (len 4) - [2,3,4,5,6]: sum=20 >= 15 (invalid) - [3,4,5]: sum=12 < 15 (len 3) - [4,5,6]: sum=15 is NOT < 15 (invalid) - [5,6]: sum=11 < 15 (len 2) The maximum length is 4.

Example 4

Input

traffic = [0, 0, 0, 0], K = 1

Output

4

Explanation: All elements are 0. The sum of the entire array is 0, which is strictly less than 1. The length of the entire array is 4. This is the maximum possible length.

Constraints

  • 1 <= traffic.length <= 10^5
  • 0 <= traffic[i] <= 10^4
  • 1 <= K <= 10^9
  • The sum of all elements in traffic may exceed 32-bit integer range, so use 64-bit integers for accumulation.

Optimal Approach & Strategy

Use a two‑pointer sliding window: maintain a running sum, expand the right pointer, and shrink from the left when the sum exceeds the threshold. Update the maximum length during the process. This runs in O(N) time and O(1) space.

Brute Force Approach

Check every possible subarray by nested loops, compute its sum, and update the maximum length if the sum is below the threshold. This takes O(N^2) time and O(1) space.

Verified Code Solutions

JavaScript Solution
Time: O(N)
function solve(traffic, K) {
    let left = 0, currentSum = 0, maxLen = -1;
    for (let right = 0; right < traffic.length; right++) {
        currentSum += traffic[right];
        while (left <= right && currentSum >= K) {
            currentSum -= traffic[left];
            left++;
        }
        if (currentSum < K && left <= right) {
            maxLen = Math.max(maxLen, right - left + 1);
        }
    }
    return maxLen;
}

Asked in Top Tech Interviews

uncategorizedmediumgeneric

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.