Skip to main content

Maximum Gap Between Stations - Solution & Explanation

MediumTwo PointersStringGreedy9 min read
Practice this problem

Problem Statement

You are given two strings skill and station of lengths n and m, respectively.

skill[i] represents the skill of worker i, and station[j] represents the skill supported by station j.

You must assign every worker to a distinct station. Let ji be the index of the station assigned to worker i. A valid assignment must satisfy:

  • station[ji] == skill[i] for every 0 <= i < n.
  • The assigned station indices must be strictly increasing in worker order, meaning j0 < j1 < ... < jn - 1.

The gap of an assignment is the maximum difference between the station indices assigned to two consecutive workers. In other words, it is max(ji - ji - 1) over all 1 <= i < n.

If there is only one worker, the gap is 0.

Return the maximum possible gap among all valid assignments. It is guaranteed that at least one valid assignment exists.

 

Example 1:

Input: skill = "aa", station = "aaaa"

Output: 3

Explanation:

  • The two workers must be assigned to two different 'a' stations.
  • Assigning them to stations [0, 3] gives a gap of 3.

Example 2:

Input: skill = "xyz", station = "xyzz"

Output: 2

Explanation:

  • Assign worker 0 to station j = 0, and worker 1 to station j = 1.
  • To maximize the gap, assign worker 2 to station j = 3.
  • This gives the assignment [0, 1, 3] with gaps [1, 2], so the gap is 2.

Example 3:

Input: skill = "cbc", station = "cbcdbc"

Output: 4

Explanation:

  • Assign worker 0 to station j = 0, and worker 1 to station j = 1.
  • To maximize the gap, assign worker 2 to station j = 5.
  • This gives the assignment [0, 1, 5] with gaps [1, 4], so the gap is 4.

 

Constraints:

  • skill.length == n
  • station.length == m
  • 1 <= n <= m <= 105
  • skill and station consist of lowercase English letters.
  • It is guaranteed that a valid assignment exists for every worker.

Approach Overview

Problem Overview: You are given a sorted list of station positions along a route. Find the maximum distance between any two consecutive stations.

Approach 1: Brute Force (O(n log n) time, O(1) space)

If the input is not guaranteed to be sorted, sort it first. Then iterate through the sorted array once, computing the difference between each adjacent pair and tracking the maximum. This approach is straightforward and works for small inputs or when you need a quick solution without worrying about performance. The sorting step dominates the time complexity, making it O(n log n).

Approach 2: Greedy Single Pass (O(n) time, O(1) space)

When the input is already sorted, you can solve this in a single pass. Maintain a variable to store the maximum gap found so far, initialized to 0. Iterate from the second element to the end, computing stations[i] - stations[i-1] and updating the maximum if the current gap is larger. This greedy approach works because the maximum gap is simply the largest adjacent difference—no other data structure or precomputation is needed. It is optimal in both time and space.

Recommended for interviews: The greedy single-pass solution is what interviewers expect. It shows you recognize that the problem reduces to finding the maximum of adjacent differences and that you can implement it cleanly in O(n) time. Mentioning the brute force first demonstrates you understand the problem's fundamentals, but the optimal solution is what sets you apart.

This problem falls under Greedy algorithms and also touches on Arrays and Two Pointers concepts when considering variations.

Solution

The maximum gap must occur between some pair of consecutive workers (i, i+1). To maximize this pair's gap, workers 0, 1, ldots, i should be assigned as far left as possible, and workers i+1, ldots, n-1 as far right as possible.

Thus, we scan from right to left and precompute suf[i]: the rightmost station worker i can take, assuming workers i+1, ldots, n-1 occupy even righter stations. Then we scan from left to right, assign worker i to the current leftmost matching station pre, and update the answer with suf[i+1] - pre.

We take the maximum over all consecutive pairs. If there is only one worker, the answer is 0.

The time complexity is O(n + m), and the space complexity is O(n), where n and m are the lengths of skill and station, respectively.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force (Sort + Scan)O(n log n)O(1)When input is unsorted or n is small
Greedy Single PassO(n)O(1)When input is already sorted or you need optimal performance

Video Solution

Leetcode 4026 | Maximum Gap Between Stations | Leetcode weekly contest 515 | Greedy • CodeWithMeGuys • 193 views views

Watch 3 more video solutions →

Frequently Asked Questions

Is Maximum Gap Between Stations easy or hard?
It is rated Medium on FleetCode with a 53.2% acceptance rate. The problem is straightforward once you realize it only requires finding the maximum adjacent difference, but it can trick you if you overcomplicate it.
How to solve Maximum Gap Between Stations in O(n)?
If the station positions are already sorted, iterate through the array once, compute each adjacent difference, and update a running maximum. This gives O(n) time and O(1) space without any additional data structures.
Maximum Gap Between Stations Python/Java solution?
In Python, initialize max_gap = 0 and loop for i in range(1, len(stations)): max_gap = max(max_gap, stations[i] - stations[i-1]). In Java, use a for loop starting at index 1 and Math.max to update the result. Both run in O(n) time.
What is the best approach for Maximum Gap Between Stations?
The best approach is a greedy single pass that computes the difference between every pair of consecutive stations and keeps track of the maximum. This runs in O(n) time and O(1) space, which is optimal because you must examine each gap at least once.
Is Maximum Gap Between Stations asked at Google/Amazon/Meta?
This problem tests fundamental array traversal and greedy thinking, which are common in technical interviews at top companies like Google, Amazon, and Meta. While it may not appear verbatim, similar problems about finding maximum differences or gaps are frequently asked.
What data structure is used in Maximum Gap Between Stations?
No complex data structure is required. The optimal solution uses only a simple array (or list) and a few variables to track the current and maximum gap. This makes it an excellent exercise for basic iteration skills.
What is the time complexity of Maximum Gap Between Stations?
The optimal solution runs in O(n) time, where n is the number of stations. If the input is unsorted and you sort it first, the time complexity becomes O(n log n) due to the sorting step.

Ready to solve this problem?

Practice Maximum Gap Between Stations with our built-in code editor and test cases.

Practice on FleetCode