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?
  1. A. 4 0 0
  2. B. 7 0 4
  3. C. 7 0 0
  4. 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

Exams that ask this topic