← Questions

Maximum tests in one activation window

0
MicrosoftCoding

A coding interview question asked at Microsoft. It tests sliding window, two pointers and sorting.

A shared test environment receives test cases over time. You are given an integer array arrivalTime, where each entry is the time one test case arrives. Several test cases can arrive at the same time.

You may turn the environment on once, at time t1, and turn it off at time t2 (t1 <= t2). Running it costs budget, so it may stay on for at most k time units: t2 - t1 <= k. Every test case whose arrival time lies in the closed interval [t1, t2] runs. Tests take no time, and tests that arrive together run together.

Implement:

def max_tests(arrival_time: list[int], k: int) -> int

Return the largest number of test cases that a single activation can run.

Constraints

  • 0 <= len(arrivalTime) <= 10^5
  • -10^9 <= arrivalTime[i] <= 10^9. The array is not sorted.
  • 0 <= k <= 2 * 10^9

Example 1

arrivalTime = [8, 2, 5, 14, 6], k = 4
Output: 3

Turn on at 2 and off at 6. The tests at 2, 5 and 6 run. No interval of length 4 holds four tests.

Example 2

arrivalTime = [3, 3, 3, 9, 11], k = 1
Output: 3

The three tests at time 3 run together, for example with [3, 4]. The tests at 9 and 11 are 2 apart, so at most one of them fits with k = 1.

Be ready to extend the solution: return the chosen (t1, t2), or allow up to m separate activations.

Clarifying questions

  • Is the window closed, so arrivals at exactly t1 and t2 run?
  • Can k be 0, so only tests arriving at the same time run together?
  • Can we sort the input in place?
  • Do we need the chosen (t1, t2)?

What a strong answer covers

  • Sorts the arrival times. An optimal window can start at an arrival.
  • Slides two pointers: for each right end, moves the left end until the span is at most k, and keeps the largest count. That is O(n log n) for the sort and O(n) for the scan.
  • Handles duplicates and negative times with no special cases.
  • Tests both examples, k = 0, the empty array, all arrivals equal, and a very large k.

Follow-ups

  • Return the chosen (t1, t2).
  • Up to m separate activations: DP over sorted arrivals with the window counts.
  • Arrivals stream in, with the best window asked at any time.
  • Each test has a run time, so a test must finish before t2.

Where it's asked

What it tests

sliding window · two pointers · sorting

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding