DSA problem
Number of People Aware of a Secret
On day 1, one person discovers a secret. You are given an integer delay: each person discovers the secret on day x will start sharing it on day x + delay with every new person they meet, sharing one new person per day. You are also given an integer forget: each person will forget the secret on day x + forget. Once forgotten, the person can no longer share the secret on or after day x + forget. Return the number of people who still know the secret at the end of day n. Since the answer may be very large, return it modulo 10^9 + 7.
The interesting structural property is that on any day d, the set of people actively sharing is exactly those who learned the secret somewhere in the window [d - forget + 1, d - delay]. Anyone older than that has already forgotten, and anyone newer than that has not started sharing yet. So we maintain a sliding-window sum over a 1D array new_learners[i] counting how many people first learn the secret on day i.
The optimal dynamic programming solution maintains a running variable sharing equal to the count of people currently sharing on day d. On day d + 1 we add to sharing the people who just became active (those who learned on day d + 1 - delay) and subtract the people who just forgot (those who learned on day d + 1 - forget). The new new_learners[d + 1] = sharing because each currently-sharing person teaches exactly one new person.
After computing the array, we sum new_learners[i] for every i in the window [n - forget + 1, n] — these are the people who still remember the secret on day n. The algorithm runs in O(n) time and O(n) space, with modular arithmetic carefully applied to avoid negative values when subtracting under the modulus.
Examples
n = 6, delay = 2, forget = 45n = 4, delay = 1, forget = 36n = 2, delay = 1, forget = 21Constraints
- 2 <= n <= 1000
- 1 <= delay < forget <= n
- Return the answer modulo 10^9 + 7.
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.