#1997

First Day Where You Have Been in All the Rooms

Medium
ArrayDynamic ProgrammingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages the observation that the room visiting sequence can be modeled as a cycle. By tracking the number of visits and the next room efficiently, we can determine the first day all rooms are visited without simulating each day.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize an array to count visits and a variable for the current room.
  2. 2Step 2: Use a loop to simulate the room visits until all rooms are visited.
  3. 3Step 3: Use a set to track visited rooms and a counter for days.
  4. 4Step 4: Return the day when all rooms have been visited.
solution.py20 lines
1# Full working Python code
2
3def firstDayVisitedAllRooms(nextVisit):
4    n = len(nextVisit)
5    visit_count = [0] * n
6    visited_rooms = set()
7    day = 0
8    current_room = 0
9    while len(visited_rooms) < n:
10        visit_count[current_room] += 1
11        visited_rooms.add(current_room)
12        if visit_count[current_room] % 2 == 1:
13            current_room = nextVisit[current_room]
14        else:
15            current_room = (current_room + 1) % n
16        day += 1
17    return day % (10**9 + 7)
18
19# Example usage:
20print(firstDayVisitedAllRooms([0, 0]))  # Output: 2

Complexity note: The optimal solution runs in O(n) time because we only loop through the rooms a limited number of times, and we use a set to track visited rooms, which allows for efficient checks.

  • 1The only way to reach room i+1 is by visiting room i an even number of times.
  • 2Tracking the number of visits allows us to determine the next room efficiently.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.