Skip to the code
cf.
+25 XP

#691 Lowest Price in Many Ranges

medium

A flight search caches a fixed list of daily fares, fares, for the next few months. The calendar widget sends many questions of the form "what is the cheapest fare from day left to day right?". The fares don't change while the widget is open.

Write cheapestFares(fares, queries) where each query is [left, right] (inclusive). Return an array with the cheapest fare for each query, in the same order. Aim for O(1) per query after some preparation.

Example 1

Input: fares = [4,6,1,5,7,3], queries = [[3,5],[0,1],[0,5]]
Output: [3,4,1]

Days 3 to 5 are 5, 7, 3, so 3; days 0 to 1 give 4; the whole list gives 1.

Example 2

Input: fares = [9], queries = [[0,0]]
Output: [9]

One day, one fare.

Constraints

  • 1 <= fares.length <= 10^5
  • 1 <= fares[i] <= 10^6
  • 0 <= queries.length <= 10^5
  • 0 <= left <= right < fares.length
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).