Most Visited Sector in a Circular Track - Problem

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, and 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.

Input & Output

Example 1 — Basic Case
$ Input: n = 4, rounds = [1,3,1,2]
Output: [1,2]
💡 Note: Marathon path: 1→2→3 (round 1), 3→4→1 (round 2), 1→2 (round 3). Sectors 1 and 2 are visited twice each, which is the maximum.
Example 2 — Wrap Around
$ Input: n = 2, rounds = [2,1,2,1,2]
Output: [2]
💡 Note: All rounds start and end at sectors 1 or 2. Following the pattern, sector 2 gets visited most frequently.
Example 3 — Single Round
$ Input: n = 7, rounds = [1,3]
Output: [1,2,3]
💡 Note: Only one round from 1 to 3, visiting sectors 1→2→3. All three sectors are visited once.

Constraints

  • 2 ≤ n ≤ 104
  • 1 ≤ rounds.length ≤ 105
  • rounds[i] is between 1 and n

Visualization

Tap to expand
Most Visited Sector in Circular Track INPUT 1 2 3 4 n = 4 sectors rounds = [1, 3, 1, 2] 1 3 1 2 Start: 1, End: 2 Counter-clockwise ALGORITHM STEPS 1 Identify Start/End start=rounds[0]=1 end=rounds[last]=2 2 Key Observation Only start and end matter for result! 3 Compare start, end If start <= end: range [start, end] 4 Apply Logic start=1, end=2 1 <= 2 is TRUE if (start <= end) return [start...end] // [1, 2] FINAL RESULT 1 2 3 4 Most Visited Sectors [1, 2] OK - Sorted Result Sectors 1 and 2 visited most frequently Key Insight: The smart observation is that intermediate rounds cancel out! Only the starting sector (rounds[0]) and ending sector (rounds[last]) determine which sectors are visited most. If start <= end, answer is [start, end]. Otherwise, answer is [1, end] + [start, n]. Time: O(n), Space: O(1). TutorialsPoint - Most Visited Sector in Circular Track | Smart Observation Approach
Asked in
Amazon 15 Google 8
28.5K Views
Medium Frequency
~15 min Avg. Time
924 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