First Day Where You Have Been in All the Rooms — LeetCode 1997 Python Solution

MediumArrayDynamic Programming
Problem
#1997
Reading time
2 min

The problem

There are n rooms you need to visit, labeled from 0 to n - 1. Each day is labeled, starting from 0.

Example

Input
nextVisit = [0,0]
Output
2
Explanation
- On day 0, you visit room 0. The total times you have been in room 0 is 1, which is odd.

Python solution

Python
class Solution:
    def firstDayBeenInAllRooms(self, nextVisit: List[int]) -> int:
        n = len(nextVisit)
        f = [0] * n
        mod = 10**9 + 7
        for i in range(1, n):
            f[i] = (f[i - 1] + 1 + f[i - 1] - f[nextVisit[i - 1]] + 1) % mod
        return f[-1]

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n), where n is the number of rooms auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1997. First Day Where You Have Been in All the Rooms is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1997. First Day Where You Have Been in All the Rooms?
LeetCode 1997. First Day Where You Have Been in All the Rooms is rated Medium on LeetCode.
What is the time complexity of LeetCode 1997. First Day Where You Have Been in All the Rooms?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1997. First Day Where You Have Been in All the Rooms?
The Python solution on this page uses O(n), where n is the number of rooms auxiliary space.
What topics does LeetCode 1997. First Day Where You Have Been in All the Rooms cover?
LeetCode 1997. First Day Where You Have Been in All the Rooms is tagged Array and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview