Minimum difference in a stream

Difficulty: HARDCategory: DSAFrequency: 1Asked On 2025-05-01

Problem Statement

You are given a stream of integers and an integer K. After each number is inserted into the stream, your task is to compute and print the minimum absolute difference between any two of the last K numbers in the stream.

If there are fewer than 2 elements in the last K numbers (i.e., total elements so far < 2), return -1.

Example

Input:

1Stream: [1, 5, 3, 8, 2] 2K = 3

Output:

1-1 // Only 1 number in window 24 // min diff = |5 - 1| = 4, so output 4 32 // Window: [1,5,3] => min diff is |5-3|=2 42 // Window: [5,3,8] => min diff is |5-3|=2 51 // Window: [3,8,2] => min diff is |2-3|=1

Final Output:

1-1 24 32 42 51


Solution

Note: The solution is left as an exercise.

One potential approach involves using the following data structures:

•A Set (or a SortedSet) to maintain the K most recent elements in sorted order, enabling efficient computation of differences between adjacent numbers.
•A Queue of size K to preserve the insertion order of elements as they arrive in the stream.
•A Min-Heap (priority queue) to efficiently track the minimum difference between any two adjacent elements in the sorted set.

This combination ensures that you can:

•Quickly insert and remove elements from the sliding window,
•Maintain a sorted view of the window for adjacent difference calculation,
•And efficiently query the minimum difference at any point.


Expected query time complexity: O(log(K))

Comments