First Day Where You Have Been in All the Rooms — LeetCode 1997 Python Solution
MediumArrayDynamic Programming
- Problem
- #1997
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.