LeetCode solutions

2316. Count Hills and Valleys in an Array

My accepted Python solution to LeetCode problem 2316, Count Hills and Valleys in an Array, running in 0ms.

  • Difficulty: Easy
  • Python
  • Runtime 0ms
  • Memory 17.5MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 0ms, memory 17.5MB, accepted 2025-12-29.

python
class Solution:
    def countHillValley(self, nums: List[int]) -> int:
        # Remove consecutive duplicates
        unique = [nums[0]]
        for i in range(1, len(nums)):
            if nums[i] != nums[i-1]:
                unique.append(nums[i])
        
        count = 0
        for i in range(1, len(unique) - 1):
            if (unique[i] > unique[i-1] and unique[i] > unique[i+1]) or                (unique[i] < unique[i-1] and unique[i] < unique[i+1]):
                count += 1
        return count

Source