Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE
Problem: A hiking trail is a list of heights. Find the length of the longest 'ridge' – a contiguous stretch that strictly rises and then strictly falls (both parts non-empty).
Problem: A hiking trail is a list of heights. Find the length of the longest 'ridge' – a contiguous stretch that strictly rises and then strictly falls (both parts non-empty).
def longest_ridge(h):
n, best, i = len(h), 0, 1
while i < n:
up = down = 0
while i < n and h[i] > h[i - 1]:
up += 1; i += 1
while i < n and h[i] < h[i - 1]:
down += 1; i += 1
if up and down:
best = max(best, up + down + 1)
if not up and not down:
i += 1
return best
print(longest_ridge([3, 5, 8, 4, 4, 1, 2, 6, 7, 3, 2, 0]), longest_ridge([9, 7, 5]), longest_ridge([1, 3, 3, 1]))What is printed?- A. 4 0 0
- B. 7 0 4
- C. 7 0 0
- D. 7 3 0
Correct answer: C. 7 0 0
Walk once: count a strictly rising run, then a strictly falling run; a ridge needs both, so its length is up + down + 1. In the first trail 3, 5, 8, 4 has length 4, but 1, 2, 6, 7, 3, 2, 0 has 3 ups and 3 downs → 7. A purely falling trail has no ridge, and a plateau (3, 3) breaks the strict rise/fall, so [1, 3, 3, 1] gives 0. The 'not up and not down' step avoids an infinite loop on flat parts. O(n).
More Coding Interview Problems questions
- Problem: Return the sum of min(sub) over all contiguous subarrays using a monotonic stack. Ties must be broken so every subarray's minimum…
- Problem: Pick two NON-overlapping windows of fixed lengths L and M (either order) to maximise the total of their elements. Prefix sums…
- Problem: Remove the SHORTEST contiguous block (not the whole array) so that the remaining sum is divisible by p; return −1 if impossible…
- Problem: Count contiguous subarrays whose MAXIMUM lies in [L, R]: count subarrays with max ≤ R and subtract those with max ≤ L − 1. python…
- Problem: Find the longest substring in which each vowel a, e, i, o, u occurs an even number of times. A 5-bit parity mask of the prefix is…
- Problem: A 3 × 3 matrix has every row and column sorted ascending. Find the k-th smallest value by binary searching on the VALUE and…