Most Visited Sector in a Circular Track

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
    def mostVisited(self, n: int, rounds: List[int]) -> List[int]:
        # Create a list to hold the counts of visits for each sector
        visits = [0] * n

        # Start from the first sector in rounds
        current_sector = rounds[0] - 1

        # Increment the visit count for the starting sector
        visits[current_sector] += 1

        # Iterate through the rounds and record the sectors visited
        for i in range(1, len(rounds)):
            while current_sector != rounds[i] - 1:
                current_sector = (current_sector + 1) % n
                visits[current_sector] += 1

        # Find the maximum number of visits
        max_visits = max(visits)

        # Return the sectors that have the maximum visits
        return [i + 1 for i, v in enumerate(visits) if v == max_visits]

Explanation

  • We keep track of visits using the visits list.
  • current_sector keeps track of the current sector in the circular loop, starting from the first sector in rounds.
  • We iterate through the rounds, incrementing the visit count for the sectors passed through.
  • Finally, we return the sectors that have the maximum visits.