Number of People Aware of a Secret - Problem
Imagine a viral secret spreading through a community with specific rules! ๐คซ
On day 1, exactly one person discovers a secret. Here's how the secret spreads:
- ๐
Each person starts sharing the secret after
delaydays from when they first learned it - ๐ง Each person forgets the secret exactly
forgetdays after discovering it - ๐ข People share the secret with one new person every day (from delay day until they forget)
- ๐ซ A person cannot share on the same day they forget or afterwards
Goal: Given integers n, delay, and forget, find how many people know the secret at the end of day n.
Since the answer can be very large, return it modulo 109 + 7.
Input & Output
example_1.py โ Basic Case
$
Input:
n = 6, delay = 2, forget = 4
โบ
Output:
5
๐ก Note:
Day 1: 1 person knows. Day 3: person starts sharing, 1 new person. Day 4: 1 person still sharing, 1 new person. Day 5: original person forgets, but 2 people from days 3,4 know, and day 3 person starts sharing, creating 1 new person. Day 6: people from days 3,4,5 still know, day 4 person starts sharing, creating 1 new person. Total: 5 people know the secret.
example_2.py โ No Sharing Case
$
Input:
n = 4, delay = 1, forget = 3
โบ
Output:
6
๐ก Note:
Day 1: 1 person. Day 2: original person shares (delay=1), +1 new = 2 total. Day 3: both share, +2 new = 4 total. Day 4: original forgets (forget=3), but 3 people from days 2,3 still know and 2 of them share, +2 new. Total knowing: people from days 2,3,4,4 = 6.
example_3.py โ Minimal Case
$
Input:
n = 1, delay = 1, forget = 2
โบ
Output:
1
๐ก Note:
Only day 1, so only 1 person knows the secret (the original discoverer). No time for sharing or forgetting.
Visualization
Tap to expand
Understanding the Visualization
1
Discovery Phase
Person learns the secret, spends 'delay' days practicing/learning
2
Sharing Phase
Person actively shares with 1 new person every day
3
Forgetting Phase
After 'forget' days total, person moves on and stops caring
4
DP Optimization
Instead of tracking individuals, track counts per discovery day
Key Takeaway
๐ฏ Key Insight: Track discovery counts per day instead of individual people to achieve optimal O(n) complexity while maintaining accurate state transitions.
Time & Space Complexity
Time Complexity
O(n)
Single pass through days 1 to n, with constant work per day
โ Linear Growth
Space Complexity
O(n)
DP array of size n to store discovery counts per day
โก Linearithmic Space
Constraints
- 2 โค n โค 1000
- 1 โค delay < forget โค n
- Answer should be returned modulo 109 + 7
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code