LeetCode Entry

2327. Number of People Aware of a Secret

09.09.2025 medium 2025 kotlin

People knowing a secret at day n, keeping delay then spread and forget

2327. Number of People Aware of a Secret medium blog post substack youtube

1.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/1107

Problem TLDR

People knowing a secret at day n, keeping delay then spread and forget #medium #simulation

Intuition

    // time, delay=1, forget = 3
    // 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
    // a a a a
    //   b b b b
    //     c c c c
    //       d d d d
    //       e
    //       f
    //       \
    //        one from a(d), one from b(e), one from c(f)
    //        3 active, so +3 passive (+delay day +3 active)

Maintain diff array for

  • changing active spreaders
  • changing knowers

Another intuition from lee: dp[i] is how many new people at that day. From that angle we know dp[i-forget] is how many people will forget today, dp[i-(forget-delay)] is how many people became active today. Very useful.

Approach

  • the main difficulty is to find a good angle to look at this problem

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(1)\)

Code


// 4ms
    fun peopleAwareOfSecret(n: Int, delay: Int, forget: Int): Int {
        val M = 1000000007L
        val know = LongArray(n+forget+1); val active = LongArray(n+forget+1)
        know[delay] = 1; know[1+forget] = -1; active[delay] = 1; active[1+forget] = -1
        for (d in 1+delay..n) {
            active[d] = (active[d-1] + active[d] + M) % M
            active[d+delay] += active[d]; active[d+forget] -= active[d]
            know[d] = (know[d-1] + know[d] + active[d] + M) % M
            know[d+forget] -= active[d]
        }
        return know[n].toInt()
    }