Skip to main content

First Day Where You Have Been in All the Rooms - Solution & Explanation

MediumArrayDynamic Programming20 min readAsked at: Bytedance
Practice this problem

Problem Statement

There are n rooms you need to visit, labeled from 0 to n - 1. Each day is labeled, starting from 0. You will go in and visit one room a day.

Initially on day 0, you visit room 0. The order you visit the rooms for the coming days is determined by the following rules and a given 0-indexed array nextVisit of length n:

  • Assuming that on a day, you visit room i,
  • if you have been in room i an odd number of times (including the current visit), on the next day you will visit a room with a lower or equal room number specified by nextVisit[i] where 0 <= nextVisit[i] <= i;
  • if you have been in room i an even number of times (including the current visit), on the next day you will visit room (i + 1) mod n.

Return the label of the first day where you have been in all the rooms. It can be shown that such a day exists. Since the answer may be very large, return it modulo 109 + 7.

 

Example 1:

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.
  On the next day you will visit room nextVisit[0] = 0
- On day 1, you visit room 0, The total times you have been in room 0 is 2, which is even.
  On the next day you will visit room (0 + 1) mod 2 = 1
- On day 2, you visit room 1. This is the first day where you have been in all the rooms.

Example 2:

Input: nextVisit = [0,0,2]
Output: 6
Explanation:
Your room visiting order for each day is: [0,0,1,0,0,1,2,...].
Day 6 is the first day where you have been in all the rooms.

Example 3:

Input: nextVisit = [0,1,2,0]
Output: 6
Explanation:
Your room visiting order for each day is: [0,0,1,1,2,2,3,...].
Day 6 is the first day where you have been in all the rooms.

 

Constraints:

  • n == nextVisit.length
  • 2 <= n <= 105
  • 0 <= nextVisit[i] <= i

Approach Overview

Problem Overview: You start in room 0 on day 0. Each room has a rule in nextVisit[i]. If you visit room i an odd number of times, you go to nextVisit[i]. If the visit count is even, you move to i + 1. The task is to compute the first day when every room from 0 to n - 1 has been visited at least once.

Approach 1: Simulation with Tracking (Time: O(days), Space: O(n))

The direct strategy simulates the process day by day. Maintain an array that counts how many times each room has been visited. On every step, increment the visit count for the current room and apply the rule: if the visit count is odd, jump to nextVisit[i]; if even, move forward to i + 1. Continue until room n - 1 is visited for the first time. This approach mirrors the problem statement exactly and is useful for understanding the behavior of the system. However, the number of simulated days can grow very large, making it impractical for big inputs.

Approach 2: Mathematical Simulation Optimization (Dynamic Programming) (Time: O(n), Space: O(n))

The key observation is that reaching room i requires repeatedly bouncing between earlier rooms due to the odd/even rule. Instead of simulating every step, track the first day each room is reached using dynamic programming. Let dp[i] be the first day you visit room i. To reach room i, you must first reach i-1, then return to nextVisit[i-1], and eventually come back to i-1 again before moving forward. This leads to the recurrence dp[i] = (2 * dp[i-1] - dp[nextVisit[i-1]] + 2) mod 1e9+7. The formula captures the round trip required to convert the odd visit of i-1 into an even visit that allows progress to the next room. Iterating through the array once computes the result efficiently.

Recommended for interviews: The dynamic programming formulation is the expected solution. Interviewers want to see the transition from naive simulation to recognizing the repeating structure of visits and deriving the recurrence. Mentioning the simulation approach first shows understanding of the rules, while implementing the DP formula demonstrates strong problem‑solving skills and complexity optimization.

Approach 1: Simulation with Tracking

This approach involves simulating each day by tracking visits with an array. We keep track of how many times each room has been visited to decide the next room to be visited based on the visit pattern given (odd or even visits). We continue this simulation until all rooms have been visited at least once.

In this C solution, we use two arrays: visits[] to count the visits to each room and visited[] to track if each room has been visited. On each day, depending on the visit count (odd or even), we decide the next room to visit. The number of days is incremented, and the main loop continues until all rooms have been visited at least once.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n^2) in the worst case because we might visit lots of rooms multiple times.
Space Complexity: O(n) due to additional arrays used for tracking visits.

Try this approach in the editor →

Approach 2: Mathematical Simulation Optimization

This approach optimizes simulation by realizing patterns and potential cycles in room visits. We use mathematical deduction to predict the days on which each new room will be discovered.

The C solution leverages mathematical progression to determine when each room will be visited. By calculating the potential day difference required for backtracking versus continuation, we achieve a direct addition pattern.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n)
Space Complexity: O(1), as we only maintain variables instead of arrays.

Try this approach in the editor →

Approach 3: Dynamic Programming

We define f[i] as the date number of the first visit to the i-th room, so the answer is f[n - 1].

Consider the date number of the first arrival at the (i-1)-th room, denoted as f[i-1]. At this time, it takes one day to return to the nextVisit[i-1]-th room. Why return? Because the problem restricts 0 leq nextVisit[i] leq i.

After returning, the nextVisit[i-1]-th room is visited an odd number of times, and the rooms from nextVisit[i-1]+1 to i-1 are visited an even number of times. At this time, we go to the (i-1)-th room again from the nextVisit[i-1]-th room, which takes f[i-1] - f[nextVisit[i-1]] days, and then it takes one more day to reach the i-th room. Therefore, f[i] = f[i-1] + 1 + f[i-1] - f[nextVisit[i-1]] + 1. Since f[i] may be very large, we need to take the remainder of 10^9 + 7, and to prevent negative numbers, we need to add 10^9 + 7.

Finally, return f[n-1].

The time complexity is O(n), and the space complexity is O(n), where n is the number of rooms.

Code

Python

Java

C++

Go

TypeScript

C#

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Simulation with Tracking

Time Complexity: O(n^2) in the worst case because we might visit lots of rooms multiple times.
Space Complexity: O(n) due to additional arrays used for tracking visits.

Mathematical Simulation Optimization

Time Complexity: O(n)
Space Complexity: O(1), as we only maintain variables instead of arrays.

Dynamic Programming—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Simulation with TrackingO(days)O(n)Useful for understanding the movement rules or validating small test cases
Mathematical Simulation Optimization (Dynamic Programming)O(n)O(n)Best choice for large inputs and the expected interview solution

Video Solution

Leetcode 1997 First Day Where You Have Been in All the Rooms • Sandip Jana • 1,483 views views

Watch 6 more video solutions →

Frequently Asked Questions

Is First Day Where You Have Been in All the Rooms easy or hard?
LeetCode classifies this problem as Medium. The challenge is not the implementation but recognizing the mathematical pattern that removes the need for full simulation. Once the recurrence is derived, the code becomes straightforward.
First Day Where You Have Been in All the Rooms Python/Java solution
Most implementations follow the same DP formula regardless of language. Create an array dp of size n, iterate from 1 to n-1, and apply the recurrence dp[i] = (2 * dp[i-1] - dp[nextVisit[i-1]] + 2) % MOD. This approach works cleanly in Python, Java, C++, and similar languages.
How to solve First Day Where You Have Been in All the Rooms in O(n)?
Use a DP array where dp[i] represents the first day room i is visited. When leaving room i-1 the first time, you must go to nextVisit[i-1], return again, and only then proceed to i. This results in the formula dp[i] = (2 * dp[i-1] - dp[nextVisit[i-1]] + 2) mod 1e9+7, which can be computed sequentially in one pass.
What is the best approach for First Day Where You Have Been in All the Rooms?
The optimal approach uses dynamic programming with a mathematical observation about the revisit pattern. Define dp[i] as the first day room i is visited. The recurrence dp[i] = (2 * dp[i-1] - dp[nextVisit[i-1]] + 2) mod 1e9+7 captures the extra loop created by the odd/even visit rule. This computes the answer in O(n) time and O(n) space.
Is First Day Where You Have Been in All the Rooms asked at Google/Amazon/Meta?
Problems involving visit simulations and recurrence relations commonly appear in interviews at companies like Google, Amazon, and Meta. Variants test whether candidates can recognize repeating patterns and convert a simulation into a dynamic programming recurrence.
What data structure is used in First Day Where You Have Been in All the Rooms?
The core data structures are arrays. The input array nextVisit defines movement rules, and a DP array stores the earliest day each room is first visited. The solution mainly relies on dynamic programming over arrays rather than complex structures like heaps or trees.
What is the time complexity of First Day Where You Have Been in All the Rooms?
The optimized dynamic programming solution runs in O(n) time because each room contributes a single DP transition. Space complexity is O(n) for storing the dp array. A naive simulation may take extremely large time since it processes every day explicitly.

Ready to solve this problem?

Practice First Day Where You Have Been in All the Rooms with our built-in code editor and test cases.

Practice on FleetCode