Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Bars of heights h[i] stand at positions i. Pick two bars that hold the most water between them (area = min height × distance).
Problem: Bars of heights h[i] stand at positions i. Pick two bars that hold the most water between them (area = min height × distance).
def most_water(h):
i, j, best = 0, len(h) - 1, 0
while i < j:
best = max(best, min(h[i], h[j]) * (j - i))
if h[i] < h[j]:
i += 1
else:
j -= 1
return best
print(most_water([2, 7, 3, 8, 4, 6, 1]))What is printed?- A. 24
- B. 28
- C. 21
- D. 14
Correct answer: A. 24
Move the shorter side inward – the taller side can never do better with a smaller width. Checked pairs: (0,6)=6, (0,5)=10, (1,5)=min(7,6)×4=24, (1,4)=12, (1,3)=14, then the pointers meet; the best is heights 7 and 6 at distance 4 = 24. Taking the two tallest bars (7 and 8, distance 2 = 14) ignores width. O(n) instead of O(n²).
More Coding Interview Problems questions
- Problem: Find the length of the longest substring of a log line with no repeated character. python def longest(s): last = {} l = best = 0…
- Problem: Find the smallest length of a contiguous block of positive integers whose sum is at least s (0 if none). python def minlen(a, s)…
- Problem: A binary array may have at most k zeros flipped to 1. Return the longest run of 1s achievable. python def longestones(a, k): l =…
- Problem: Return the maximum of every window of size k in a stream of readings. python from collections import deque def winmax(a, k): dq…
- Problem: For n = 10⁶ readings and window size k = 10⁵, report every window maximum. Which approach fits the limits best?
- Problem: Count how many substrings of length k in a DNA string contain exactly k distinct letters. python def countdistinct(s, k): freq, c…