You are given an integer n
and an integer array rounds
. There is a circular track which consists of n
sectors labeled from 1
to n
. A marathon runner starts at sector rounds[0]
and runs in the clockwise direction sequentially through rounds
. The runner finishes at the position rounds[rounds.length - 1]
. The task is to find the most visited sectors in the track. You need to return these sectors sorted in ascending order.
rounds
array, or is it just one continuous run?
rounds
array represents one continuous run.rounds
array will have at least two elements, i.e., a start and an end sector?
rounds
be greater than the number of sectors n
?
rounds
and sequentially goes through the track according to the given array, we will simulate this movement and count visits to each sector.Given that the track is circular:
rounds[i]
is less than rounds[i-1]
, it implies that the runner passes the sector n
and starts from 1 again.rounds
array to simulate the track traversal and count sector visits.def most_visited(n, rounds):
# Initialize sector visit counts
visit_counts = [0] * (n + 1)
# Track sectors visited during each round
start = rounds[0]
for end in rounds:
if start <= end:
for sector in range(start, end + 1):
visit_counts[sector] += 1
else:
for sector in range(start, n + 1):
visit_counts[sector] += 1
for sector in range(1, end + 1):
visit_counts[sector] += 1
start = end
# Find maximum visit count
max_visit = max(visit_counts)
# Extract sectors with the maximum visit count
result = [i for i in range(1, n + 1) if visit_counts[i] == max_visit]
return sorted(result)
# Example usage
n = 4
rounds = [1, 3, 1, 2]
print(most_visited(n, rounds)) # Output: [1, 2]
rounds
array once, iterating through sectors between two points in each step which is dominated by n
, resulting in O(m + n)
, where m
is the length of rounds
.n
sectors and extracting sectors, which is O(n)
.Therefore, the overall time complexity is O(m + n)
.
The space complexity is O(n)
for the visit_counts
array.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?