Ctrl K

Best Floor for Every Width

Medium
You are given an array heights of length n. For each width w from 1 to n, look at every contiguous stretch of the array with length w, take the minimum of each, and pick the largest of those minimums. Return an array of length n whose entry at index w - 1 is the answer for width w. The direct approach is O(n²); try to get it down to O(n).
Example 1
heights=[3, 1, 4, 2] → [4, 2, 1, 1]

Width 1: the best minimum is 4. Width 2: windows [3,1], [1,4], [4,2] give 1, 1, 2, so the best is 2. Widths 3 and 4: every window contains the 1.

Example 2
heights=[5, 6, 6, 5] → [6, 6, 5, 5]

The window [6, 6] gives a minimum of 6 at width 2; at width 3 every window already contains a 5.

Constraints
  • 1 ≤ n ≤ 10⁵
  • 0 ≤ heights[i] ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPreorder of a Search Tree MediumLow, Peak, Middle MediumNext Larger Around the Circle MediumFix the Middle of the Line MediumPeak-Split Tree Medium
loading Python…
Input
heights=[3, 1, 4, 2]
Expected
[4, 2, 1, 1]

Run checks the first 3 tests in your browser. Submit checks all 142 tests on the server, hidden ones included.