Data Structures & AlgorithmsModerateTCS NQT · array basics

Problem: How many peaks (elements strictly greater than both neighbours, excluding the two ends) does [1, 3, 2, 4, 1, 5] have? Run the code.

Problem: How many peaks (elements strictly greater than both neighbours, excluding the two ends) does [1, 3, 2, 4, 1, 5] have? Run the code.
a = [1, 3, 2, 4, 1, 5]
print(sum(1 for i in range(1, len(a) - 1) if a[i] > a[i - 1] and a[i] > a[i + 1]))
What is printed?
  1. A. 1
  2. B. 2
  3. C. 3
  4. D. 0

Correct answer: B. 2

The peaks are 3 at index 1 and 4 at index 3. The value 5 is at an end and cannot be a peak under this definition.

More Coding Interview Problems questions

Exams that ask this topic