LeetCode solutions

2124. First Day Where You Have Been in All the Rooms

My accepted Python solution to LeetCode problem 2124, First Day Where You Have Been in All the Rooms, running in 106ms.

  • Difficulty: Medium
  • Python
  • Runtime 106ms
  • Memory 29.3MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 106ms, memory 29.3MB, accepted 2025-12-29.

python
class Solution:
    def firstDayBeenInAllRooms(self, nextVisit: List[int]) -> int:
        MOD = 10**9 + 7
        n = len(nextVisit)
        # dp[i] = first day to reach room i for the first time
        dp = [0] * n
        
        for i in range(1, n):
            # To reach room i, we first need to reach room i-1
            # Then we need to revisit room nextVisit[i-1] (odd visit to room i-1)
            # Then we need to go from nextVisit[i-1] to i-1 again
            # Then on even visit to i-1, we go to room i
            dp[i] = (2 * dp[i-1] - dp[nextVisit[i-1]] + 2) % MOD
        
        return dp[n-1]

Source