Count Balance Windows Whose Average Meets a Required Threshold

Last updated: November 29, 2026

Quick Overview

Given an array of daily account balances and a threshold k, count the number of contiguous non-empty windows of days whose average balance is at least k, for arrays up to 10^5 days.

TCS
Coding & Algorithms
Software Engineer
TCS
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


Given an array of daily account balances and a threshold k, count the number of contiguous non-empty windows of days whose average balance is at least k, for arrays up to 10^5 days.

Average monthly balance rules drive fee waivers and eligibility checks in the core banking systems TCS builds, and this is the harder algorithmic version of that idea. The interviewer looks for the shift by k, the prefix-sum reduction to counting non-inversions, and an O(N log N) count via merge sort or a Fenwick tree.

What the Interviewer Expects
  • Subtract k from every value to turn average into sum >= 0
  • Reduce to counting pairs i < j with prefix[i] <= prefix[j]
  • Count pairs in O(N log N) with merge sort or a BIT
  • Include the empty prefix 0 so windows starting at day 0 count
  • Verify against a brute force on small inputs
Key Topics to Cover
Prefix sums
Merge sort counting
Inversions
Fenwick tree
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you do it with a Fenwick tree and coordinate compression?
  • How do you restrict to windows of length at least L?
  • What if k is fractional and balances are large integers, how do you avoid float error?
  • How would you answer many different k values on the same array?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements

Window [i, j) qualifies when 1j−i∑a≥k\frac{1}{j-i}\sum a \ge k, which is equivalent to ∑(a−k)≥0\sum (a - k) \ge 0. With P0=0P_0 = 0 and Pj=∑t<j(at−k)P_j = \sum_{t<j}(a_t - k), a window qualifies iff Pi≤PjP_i \le P_j for $i < j...

High-Level Design

Brute force is O(N^2). Instead, run merge sort on the prefix array. When merging, every element in the left half has a smaller index than every element in the right half, so for each right element cou...


Submit Your Answer
Markdown supported

Related Questions