Leetcode 1997: First Day Where You Have Been in All the Rooms

grid47
grid47
Exploring patterns and algorithms
Apr 21, 2024 5 min read

You are given a list of rooms and their visiting order for each day based on a set of rules. On each day, you either revisit a room based on the number of visits or proceed to the next room in a cyclic manner. Your task is to find the first day when all rooms have been visited.
Problem
Approach
Steps
Complexity
Input: The input consists of a list 'nextVisit' of length n (2 <= n <= 100,000), where each element is an integer indicating the next room to visit based on the rules provided.
Example: nextVisit = [0, 0]
Constraints:
• 2 <= n <= 100,000
• 0 <= nextVisit[i] <= i
Output: Return the first day when all rooms have been visited. The answer should be returned modulo 10^9 + 7.
Example: 2
Constraints:
Goal: We need to track how many times each room is visited and determine when all rooms have been visited at least once.
Steps:
• 1. Use dynamic programming (dp) to track the total number of visits up to each day.
• 2. For each room, depending on whether it has been visited an even or odd number of times, decide the next room to visit.
• 3. Continue until all rooms have been visited at least once, then return the day modulo 10^9 + 7.
Goal: The input list must meet the following constraints to ensure valid input and efficient processing.
Steps:
• The list 'nextVisit' has length between 2 and 100,000.
• Each element in 'nextVisit' is between 0 and the index of that element.
Assumptions:
• The input list will always contain valid values.
Input: nextVisit = [0, 0]
Explanation: On day 0, you visit room 0. On day 1, you visit room 0 again, and on day 2, you visit room 1, completing the visit to all rooms.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus