Most Visited Sector in a Circular Track Problem
Description
LeetCode Problem 1560.
Given an integer n and an integer array rounds. We have a circular track which consists of n sectors labeled from 1 to n. A marathon will be held on this track, the marathon consists of m rounds. The i^th round starts at sector rounds[i - 1] and ends at sector rounds[i]. For example, round 1 starts at sector rounds[0] and ends at sector rounds[1]
Return an array of the most visited sectors sorted in ascending order.
Notice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example).
Example 1:

Input: n = 4, rounds = [1,3,1,2]
Output: [1,2]
Explanation: The marathon starts at sector 1. The order of the visited sectors is as follows:
1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon)
We can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once.
Example 2:
Input: n = 2, rounds = [2,1,2,1,2,1,2,1,2]
Output: [2]
Example 3:
Input: n = 7, rounds = [1,3,5,7]
Output: [1,2,3,4,5,6,7]
Constraints:
2 <= n <= 1001 <= m <= 100rounds.length == m + 11 <= rounds[i] <= nrounds[i] != rounds[i + 1]for0 <= i < m
Solution
Approach: Only the Start and the End Matter
The rounds chain together: each round starts where the previous one ended. So the whole marathon is one continuous walk from rounds[0] to rounds[m], counter-clockwise.
That walk consists of some number of full laps plus one partial walk from the start sector to the end sector. Full laps visit every sector the same number of times, so they do not change which sectors are most visited. The partial walk, including both its start and end sectors, gets one extra visit. Where it lies depends on how start = rounds[0] and end = rounds[m] compare:
start <= end: the sectorsstart, start + 1, ..., end.start > end: the walk wraps pastn, so it covers1..endandstart..n. Listing1..endfirst keeps the result in ascending order.
For Example 1, the walk goes from 1 to 2, so the answer is [1, 2], even though the track was circled once in between.
Complexity: O(n) time for the output, and O(1) extra space besides it.
class Solution:
def mostVisited(self, n: int, rounds: List[int]) -> List[int]:
start, end = rounds[0], rounds[-1]
# Full laps visit every sector equally; only the walk from start to end adds one extra visit.
if start <= end:
return list(range(start, end + 1))
return list(range(1, end + 1)) + list(range(start, n + 1))