Skip to main content

Custom Interval - Solution & Explanation

MediumPremiumFree on FleetCode4 min read
Practice this problem

Problem Statement

Function customInterval

Given a function fn, a number delay and a number period, return a number id.

customInterval is a function that should execute the provided function fn at intervals based on a linear pattern defined by the formula delay + period * count

The count in the formula represents the number of times the interval has been executed starting from an initial value of 0.

Function customClearInterval 

Given the id. id is the returned value from the function customInterval.

customClearInterval should stop executing provided function fn at intervals.

Note: The setTimeout and setInterval functions in Node.js return an object, not a number.

 

Example 1:

Input: delay = 50, period = 20, cancelTime = 225
Output: [50,120,210]
Explanation: 
const t = performance.now()  
const result = []
        
const fn = () => {
    result.push(Math.floor(performance.now() - t))
}
const id = customInterval(fn, delay, period)
        
setTimeout(() => {
    customClearInterval(id)
}, 225)

50 + 20 * 0 = 50 // 50ms - 1st function call
50 + 20 * 1 = 70 // 50ms + 70ms = 120ms - 2nd function call
50 + 20 * 2 = 90 // 50ms + 70ms + 90ms = 210ms - 3rd function call

Example 2:

Input: delay = 20, period = 20, cancelTime = 150
Output: [20,60,120]
Explanation: 
20 + 20 * 0 = 20 // 20ms - 1st function call
20 + 20 * 1 = 40 // 20ms + 40ms = 60ms - 2nd function call
20 + 20 * 2 = 60 // 20ms + 40ms + 60ms = 120ms - 3rd function call

Example 3:

Input: delay = 100, period = 200, cancelTime = 500
Output: [100,400]
Explanation: 
100 + 200 * 0 = 100 // 100ms - 1st function call
100 + 200 * 1 = 300 // 100ms + 300ms = 400ms - 2nd function call

 

Constraints:

  • 20 <= delay, period <= 250
  • 20 <= cancelTime <= 1000

Approach Overview

Problem Overview: You’re given a collection of intervals and a custom interval. The goal is to determine how this interval fits into the existing set—typically by inserting it and merging overlaps so the final result remains a valid list of non‑overlapping intervals.

Approach 1: Brute Force Overlap Checking (O(n^2) time, O(n) space)

Start by adding the custom interval to the list of existing intervals. Then repeatedly scan the array to detect overlapping pairs. Whenever two intervals overlap, merge them into a single interval and restart the scan. This method relies on repeated comparisons between interval boundaries (start and end). While simple to reason about, the nested scanning leads to quadratic time complexity when many intervals overlap.

Approach 2: Sort and Merge Intervals (O(n log n) time, O(n) space)

Append the custom interval to the interval list and sort all intervals by their starting value. Then iterate through the sorted list and maintain a result array. For each interval, compare it with the last merged interval in the result. If the current interval overlaps (current.start <= last.end), update the end boundary using Math.max. Otherwise, push the interval as a new segment. Sorting ensures that overlapping intervals appear next to each other, allowing a single linear pass to merge them efficiently. This pattern frequently appears in interval problems and scheduling tasks.

Approach 3: Sweep Line Processing (O(n log n) time, O(n) space)

Convert each interval boundary into events: a start event and an end event. Include the custom interval in this event list. Sort events by position and process them sequentially while tracking the number of active intervals. When the active count moves from zero to one, a new merged interval begins; when it returns to zero, the interval ends. This technique—commonly called a sweep line—generalizes well for more complex interval counting or overlap queries.

Recommended for interviews: The sort‑and‑merge approach is the standard expectation. It demonstrates understanding of interval ordering, boundary comparisons, and linear merging. Brute force shows baseline reasoning, but the optimal O(n log n) solution using sorting is what interviewers typically look for in problems involving arrays and interval manipulation.

Solution

Code

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Overlap CheckingO(n^2)O(n)Small datasets or when demonstrating basic overlap logic
Sort and Merge IntervalsO(n log n)O(n)General case for inserting or merging intervals
Sweep Line TechniqueO(n log n)O(n)Useful when tracking overlap counts or handling many interval events

Video Solution

How many LeetCode problems should you solve? #leetcode #techinterview #developer #softwareengineerCrioDo304,684 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Custom Interval easy or hard?
Custom Interval is generally classified as a medium-level problem. The logic becomes straightforward once you recognize the interval merge pattern, but correctly handling overlap boundaries and sorting behavior can trip up beginners.
Custom Interval Python/Java solution
A typical implementation sorts intervals by start value and iterates through them while maintaining a result list. If the current interval overlaps with the last merged interval, update the end boundary; otherwise append it. The same logic works across Python, Java, TypeScript, and C++ with O(n log n) complexity.
How to solve Custom Interval in O(n)?
O(n) is achievable only if the intervals are already sorted by start time. In that case, iterate through the list and merge the custom interval as you go, updating boundaries when overlaps occur. Without pre-sorted intervals, sorting dominates the complexity.
What is the best approach for Custom Interval?
The standard approach is sorting the intervals and merging overlaps. Insert the custom interval into the list, sort by start value, then iterate once to merge overlapping ranges. This runs in O(n log n) time due to sorting and O(n) space for the merged result.
Is Custom Interval asked at Google/Amazon/Meta?
Interval merging and insertion patterns appear frequently in interviews at companies like Google, Amazon, and Meta. While the exact problem title may vary, the underlying technique—sorting intervals and merging overlaps—is a common interview topic.
What data structure is used in Custom Interval?
The solution primarily uses arrays or lists to store intervals and the merged results. Sorting utilities and simple comparisons between start and end values are enough. No advanced structures are required beyond standard array traversal.
What is the time complexity of Custom Interval?
The optimal solution runs in O(n log n) time because the intervals must be sorted by their start boundary before merging. After sorting, the merge step only requires a single linear pass, which is O(n). Space complexity is typically O(n) for the result list.

Ready to solve this problem?

Practice Custom Interval with our built-in code editor and test cases.

Practice on FleetCode