Talentd
FleetCode
Make and follow sheets.Sign in

First Day Where You Have Been in All the Rooms solution and explanation

MediumArrayDynamic Programming6 min read40.5% acceptanceUpdated 9 Apr 2026
Leetcode 1997 First Day Where You Have Been in All the RoomsSandip Jana · 15:06 · 1K viewsWatch on YouTube
6 more videos on this problem
  1. Leetcode 1997 First Day Where You Have Been in All the RoomsSandip Jana · 15:06 · 1K views
  2. LeetCode 1997. First Day Where You Have Been in All the RoomsHappy Coding · 11:31 · 1K views
  3. 1997. First Day Where You Have Been in All the Rooms (Leetcode Medium)Programming Live with Larry · 43:01 · 523 views
  4. 【每日一题】LeetCode 1997. First Day Where You Have Been in All the Rooms, 9/14/2021Huifeng Guan · 15:11 · 488 views
  5. Leetcode 1997 First Day Where You Have Been in All the RoomsMath Geeks · 7:40 · 123 views
  6. 1997. (Medium) First Day Where You Have Been in All the Rooms (Day 90)yeetcode · 8:24 · 94 views
  7. LeetCode 1997: First Day Where You Have Been in All the RoomsAlitaCode · 25:40 · 5 views

The problem

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.

def first_day_all_rooms(nextVisit):
    MOD = 10**9 + 7
    n = len(nextVisit)
    visit_count = [0] * n
    visited = [False] * n
    visited[0] = True
    visited_count = 1
    day = 0
    current_room = 0
    
    while visited_count < n:
        visit_count[current_room] += 1
        day = (day + 1) % MOD
        if visit_count[current_room] % 2 != 0:
            current_room = nextVisit[current_room]
        else:
            current_room = (current_room + 1) % n

        if not visited[current_room]:
            visited[current_room] = True
            visited_count += 1

    return day

next_visit = [0, 0, 2]
print(first_day_all_rooms(next_visit))
import java.util.Arrays;

public class FirstDayAllRooms {
    private static final int MOD = 1000000007;

    public static int firstDayAllRooms(int[] nextVisit) {
        int n = nextVisit.length;
        int[] visitCount = new int[n];
        boolean[] visited = new boolean[n];
        int visitedCount = 1, day = 0, currentRoom = 0;
        visited[0] = true;
        
        while (visitedCount < n) {
            visitCount[currentRoom]++;
            day = (day + 1) % MOD;
            if (visitCount[currentRoom] % 2 != 0) {
                currentRoom = nextVisit[currentRoom];
            } else {
                currentRoom = (currentRoom + 1) % n;
            }
            if (!visited[currentRoom]) {
                visited[currentRoom] = true;
                visitedCount++;
            }
        }
        return day;
    }

    public static void main(String[] args) {
        int[] nextVisit = {0, 0, 2};
        System.out.println(firstDayAllRooms(nextVisit));
    }
}
#include <iostream>
#include <vector>

const int MOD = 1000000007;

int firstDayAllRooms(std::vector<int>& nextVisit) {
    int n = nextVisit.size();
    std::vector<int> visitCount(n, 0);
    std::vector<bool> visited(n, false);
    int visitedCount = 1, day = 0, currentRoom = 0;

    visited[0] = true;

    while (visitedCount < n) {
        visitCount[currentRoom]++;
        day = (day + 1) % MOD;
        if (visitCount[currentRoom] % 2 != 0) {
            currentRoom = nextVisit[currentRoom];
        } else {
            currentRoom = (currentRoom + 1) % n;
        }
        if (!visited[currentRoom]) {
            visited[currentRoom] = true;
            visitedCount++;
        }
    }
    return day;
}

int main() {
    std::vector<int> nextVisit = {0, 0, 2};
    std::cout << firstDayAllRooms(nextVisit) << std::endl;
    return 0;
}
function firstDayAllRooms(nextVisit) {
    const MOD = 1000000007;
    const n = nextVisit.length;
    const visitCount = Array(n).fill(0);
    const visited = Array(n).fill(false);
    visited[0] = true;
    let visitedCount = 1;
    let day = 0;
    let currentRoom = 0;

    while (visitedCount < n) {
        visitCount[currentRoom]++;
        day = (day + 1) % MOD;
        if (visitCount[currentRoom] % 2 !== 0) {
            currentRoom = nextVisit[currentRoom];
        } else {
            currentRoom = (currentRoom + 1) % n;
        }
        if (!visited[currentRoom]) {
            visited[currentRoom] = true;
            visitedCount++;
        }
    }

    return day;
}

console.log(firstDayAllRooms([0, 0, 2]));
#include <stdio.h>
#define MOD 1000000007

int firstDayAllRooms(int* nextVisit, int n) {
    int visits[n], visited[n], visitedCount = 1; // room 0 visited on day 0
    for (int i = 0; i < n; i++) visits[i] = 0, visited[i] = 0;
    
    int day = 0, currentRoom = 0;
    visited[0] = 1;

    while (visitedCount < n) {
        visits[currentRoom]++;
        day = (day + 1) % MOD;
        
        if (visits[currentRoom] % 2 != 0) {
            currentRoom = nextVisit[currentRoom];
        } else {
            currentRoom = (currentRoom + 1) % n;
        }
        
        if (!visited[currentRoom]) {
            visited[currentRoom] = 1;
            visitedCount++;
        }
    }
    return day;
}

int main() {
    int nextVisit[] = {0, 0, 2};
    int n = sizeof(nextVisit) / sizeof(nextVisit[0]);
    printf("%d\n", firstDayAllRooms(nextVisit, n));
    return 0;
}
using System;

class FirstDayAllRooms {
    private static int MOD = 1000000007;

    public static int FirstDayAllRooms(int[] nextVisit) {
        int n = nextVisit.Length;
        int[] visitCount = new int[n];
        bool[] visited = new bool[n];
        int visitedCount = 1, day = 0, currentRoom = 0;
        visited[0] = true;

        while (visitedCount < n) {
            visitCount[currentRoom]++;
            day = (day + 1) % MOD;
            if (visitCount[currentRoom] % 2 != 0) {
                currentRoom = nextVisit[currentRoom];
            } else {
                currentRoom = (currentRoom + 1) % n;
            }
            if (!visited[currentRoom]) {
                visited[currentRoom] = true;
                visitedCount++;
            }
        }
        return day;
    }

    public static void Main(string[] args) {
        int[] nextVisit = {0, 0, 2};
        Console.WriteLine(FirstDayAllRooms(nextVisit));
    }
}

The Python code uses list structures for visit tracking. It increments days and manages room visits with conditions based on even or odd visit counts, leveraging Python's simplicity for integer operations.

Complexity

Time Complexity: O(n^2) due to nested conditions causing multiple room visits.
Space Complexity: O(n) from extra lists.

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.

def first_day_all_rooms(nextVisit):
    MOD = 10**9 + 7
    day = 0
    for i in range(1, len(nextVisit)):
        day = (day + 1) + ((day - nextVisit[i]) % MOD)
        day %= MOD
    return day

next_visit = [0, 0, 2]
print(first_day_all_rooms(next_visit))
public class FirstDayAllRoomsOptimized {
    private static final int MOD = 1000000007;

    public static int firstDayAllRooms(int[] nextVisit) {
        long day = 0;  // long to prevent overflow
        for (int i = 1; i < nextVisit.length; i++) {
            day = (day + 1) + ((day - nextVisit[i]) % MOD);
            day %= MOD;
        }
        return (int) day;
    }

    public static void main(String[] args) {
        int[] nextVisit = {0, 0, 2};
        System.out.println(firstDayAllRooms(nextVisit));
    }
}
#include <iostream>
#include <vector>
using namespace std;

const int MOD = 1000000007;

int firstDayAllRooms(vector<int>& nextVisit) {
    long long day = 0;  // Using long long to avoid overflow
    for (int i = 1; i < nextVisit.size(); ++i) {
        day = (day + 1) + (day - nextVisit[i]) % MOD;
        day %= MOD;
    }
    return day;
}

int main() {
    vector<int> nextVisit = {0, 0, 2};
    cout << firstDayAllRooms(nextVisit) << endl;
    return 0;
}
function firstDayAllRooms(nextVisit) {
    const MOD = 1000000007;
    let day = 0;
    for (let i = 1; i < nextVisit.length; i++) {
        day = (day + 1) + ((day - nextVisit[i]) % MOD);
        day %= MOD;
    }
    return day;
}

console.log(firstDayAllRooms([0, 0, 2]));
#include <stdio.h>
#define MOD 1000000007

int firstDayAllRooms(int* nextVisit, int n) {
    long long day = 0;  // Using long long to prevent overflow
    for (int i = 1; i < n; ++i) {
        day = (day + 1) + (day - nextVisit[i]) % MOD;
        day = day % MOD;
    }
    return (int) day;
}

int main() {
    int nextVisit[] = {0, 0, 2};
    int n = sizeof(nextVisit) / sizeof(nextVisit[0]);
    printf("%d\n", firstDayAllRooms(nextVisit, n));
    return 0;
}
using System;

class FirstDayAllRoomsOptimized {
    private static int MOD = 1000000007;

    public static int FirstDayAllRooms(int[] nextVisit) {
        long day = 0;  // Using long to handle large sums
        for (int i = 1; i < nextVisit.Length; i++) {
            day = (day + 1) + (day - nextVisit[i]) % MOD;
            day %= MOD;
        }
        return (int) day;
    }

    public static void Main(string[] args) {
        int[] nextVisit = {0, 0, 2};
        Console.WriteLine(FirstDayAllRooms(nextVisit));
    }
}

The Python approach adapts the mathematical insight for rapid computation. By managing day counts using modular arithmetic, we ensure robustness across arbitrary sizes of input.

Complexity

Time Complexity: O(n)
Space Complexity: O(1), as we rely on built-in handling of integers.

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.

function firstDayBeenInAllRooms(nextVisit: number[]): number {
    const n = nextVisit.length;
    const mod = 1e9 + 7;
    const f: number[] = new Array<number>(n).fill(0);
    for (let i = 1; i < n; ++i) {
        f[i] = (f[i - 1] + 1 + f[i - 1] - f[nextVisit[i - 1]] + 1 + mod) % mod;
    }
    return f[n - 1];
}
func firstDayBeenInAllRooms(nextVisit []int) int {
	n := len(nextVisit)
	f := make([]int, n)
	const mod = 1e9 + 7
	for i := 1; i < n; i++ {
		f[i] = (f[i-1] + 1 + f[i-1] - f[nextVisit[i-1]] + 1 + mod) % mod
	}
	return f[n-1]
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Simulation with Tracking

Time Complexity: O(n^2) due to nested conditions causing multiple room visits.
Space Complexity: O(n) from extra lists.

Mathematical Simulation Optimization

Time Complexity: O(n)
Space Complexity: O(1), as we rely on built-in handling of integers.

Dynamic Programming–

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

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.

Comments

Now write it yourselfClose this page and solve First Day Where You Have Been in All the Rooms in the editor, without looking.
Practise First Day Where You Have Been in All the Rooms