AlgoMaster Logo

Smallest Range Covering Elements from K Lists

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. Priority Queue (Heap) Approach

Intuition:

The problem requires finding the smallest range that includes at least one number from each of K lists. We can use a min-heap to efficiently track the smallest current number across all lists and try to widen our range by tracking maximum elements simultaneously.

  1. Initialize a min-heap and add the first element of each list along with its index.
  2. Track the current maximum number across list frontrunners.
  3. Expand the smallest number (from the heap) by pulling the next element from the same list.
  4. Update and check the range every time the heap is updated.

Code:

2. Two Pointers with Sorted List

Intuition:

By flattening all lists into a single sorted list while keeping track of their origins, we can use a two-pointer technique to identify the smallest range covering all lists.

  1. Flatten the list with additional information to identify elements' origin.
  2. Use two pointers to scan through the list and check complete coverage.
  3. Attempt to shrink the range by moving the left pointer once coverage is ensured.

Code: