First Day Where You Have Been in All the Rooms - 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 10^9 + 7.

Input & Output

Example 1 — Basic Two Rooms
$ Input: nextVisit = [0,0]
Output: 2
💡 Note: Day 0: visit room 0 (1st time) → next: room 0. Day 1: visit room 0 (2nd time) → next: room 1. Day 2: visit room 1 (1st time) → all rooms visited, return 2
Example 2 — Three Rooms
$ Input: nextVisit = [0,0,2]
Output: 6
💡 Note: Must visit room 0 and 1 multiple times before reaching room 2 for the first time on day 6
Example 3 — Single Room
$ Input: nextVisit = [0]
Output: 0
💡 Note: Only one room, visited on day 0, so return 0

Constraints

  • 1 ≤ nextVisit.length ≤ 105
  • 0 ≤ nextVisit[i] ≤ i

Visualization

Tap to expand
First Day to Visit All Rooms INPUT Rooms: 0 to n-1 0 1 nextVisit Array: 0 i=0 0 i=1 Visit Rules: Odd visits: go to nextVisit[i] Even visits: go to (i+1) mod n nextVisit = [0, 0], n = 2 ALGORITHM STEPS 1 Day 0: Visit Room 0 1st visit (odd) --> next: room 0 2 Day 1: Visit Room 0 2nd visit (even) --> next: room 1 3 Day 2: Visit Room 1 1st visit to room 1 - All visited! 4 DP Formula dp[i] = first day to reach room i DP Table: dp[0] 0 dp[1] 2 dp[i+1] = 2*dp[i] - dp[next[i]] + 2 dp[1] = 2*0 - 0 + 2 = 2 FINAL RESULT Visit Timeline: Day 0: 0 Visit room 0 Day 1: 0 Visit room 0 Day 2: 1 All visited! OUTPUT 2 First day all rooms visited OK - Answer: 2 Key Insight: Each room must be visited an even number of times before moving to the next room. Use DP where dp[i] represents the first day to reach room i. The recurrence relation captures that visiting room i twice requires returning to nextVisit[i] and working back. Time: O(n), Space: O(n). TutorialsPoint - First Day Where You Have Been in All the Rooms | Dynamic Programming Approach
Asked in
Google 15 Microsoft 12
23.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen