KatInterview

Indices of Ranges Fully Inside a Query Range

Greedy & IntervalsAuto-graded · 17 test cases
EasyAuto-gradedGreedy & Intervalsintervalsarrayscan

Last updated

Scan a list of closed integer ranges and return the indices of those lying entirely within a given query range, testing inclusive boundary handling.

Ranges Inside a Query Range

You have a list ranges of closed integer ranges. Each entry is a pair [lo, hi] with lo <= hi. You are also given a query range query = [query_lo, query_hi].

A range [lo, hi] is inside the query range when it does not extend past either end of the query, that is, when both of these hold:

  • query_lo <= lo
  • hi <= query_hi

Both comparisons are inclusive. A range that shares an endpoint with the query still counts, and a range identical to the query counts too.

Return the 0-based positions (indices into ranges) of every range that is inside the query range, in ascending order. If no range qualifies, return an empty list.

Constraints

  • 1 <= len(ranges) <= 10^5
  • ranges[i][0] <= ranges[i][1] for every i
  • All endpoint values are integers (they may be negative or large).
  • query has exactly two integers, query[0] and query[1], with query[0] <= query[1].
  • Each index appears at most once in the result.

Examples

Example 1

Input: indices_inside_range([[1, 3], [2, 5], [6, 7], [4, 4]], [1, 5])

Output: [0, 1, 3]

Example 2

Input: indices_inside_range([[10, 20], [1, 5]], [2, 8])

Output: []

Hints

Hint 1

Write down exactly what has to be true about the left end and about the right end of a range for it to lie inside the query.

Hint 2

Because each range satisfies lo <= hi, two inclusive comparisons are enough. Use <= rather than < so touching endpoints count.

Hint 3

Walk through the list once in index order, keeping the index of each range that passes both checks. The output is then automatically ascending.