703318. Tracks

Easy

Here is the detailed Markdown blog post for the GeeksforGeeks problem "Tracks":

Tracks

Summary

The problem involves finding the maximum number of tracks that can be formed in a given set of intervals. The intervals are represented as pairs of integers, where each pair represents a track with a start and end time. The goal is to find the maximum number of non-overlapping tracks that can be formed.

Detailed Explanation

To solve this problem, we will use an array-based approach. We initialize a variable max_tracks to store the maximum number of tracks found so far. Then, we iterate over each interval in the input array. For each interval, we check if it does not overlap with any previously selected track by checking its start time is greater than or equal to the end time of the previous track. If the current interval does not overlap, we increment max_tracks and update the end time of the last selected track.

Here's a step-by-step breakdown:

  1. Initialize max_tracks to 0.
  2. Iterate over each interval in the input array.
  3. For each interval, check if its start time is greater than or equal to the end time of the previous track (if any).
  4. If the current interval does not overlap with the previous track, increment max_tracks and update the end time of the last selected track.
  5. Return max_tracks.

Time complexity: O(n), where n is the number of intervals in the input array.

Space complexity: O(1), as we only use a constant amount of space to store the maximum number of tracks found so far.

Here's an ASCII art diagram illustrating the algorithm:

  +---------------+
  |  Interval 1  |
  +---------------+
           ^
  |  Interval 2  |
  +---------------+
           ^
  ...
  |  Interval n  |
  +---------------+

  Tracks: [Interval 1, Interval 3, ...]
  End time of last track: end_time_of_interval_1

Optimized Solutions

Java

View on GeeksforGeeks
public int maxTracks(int[][] intervals) {
    if (intervals.length == 0) return 0;
    
    int max_tracks = 0;
    int end_time = -1; // Initialize with negative infinity
    
    for (int[] interval : intervals) {
        if (interval[0] >= end_time) { // No overlap
            max_tracks++;
            end_time = interval[1];
        }
    }
    
    return max_tracks;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.