↓Skip to main content
  1. LeetCode/

LeetCode 2210: Count Hills and Valleys in an Array

·1 min· ·
LeetCode Easy Array
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2025-07-27

  • Submissions: Accepted (first try)

Approach
#

Equal neighbors belong to the same hill or valley, so look only at directions: each adjacent pair goes up, down or flat (Array Template 1). Skip flat pairs and remember the last non-flat direction; up turning down is a hill, down turning up a valley.

My Solution
#

class Solution:
    def countHillValley(self, nums: List[int]) -> int:
        res, prev = 0, 0                       # prev:上一個不平的方向,1 上、-1 下
        for a, b in zip(nums, nums[1:]):
            d = (b > a) - (b < a)
            if d == 0:
                continue
            if prev and d != prev:
                res += 1
            prev = d
        return res

I originally stored the directions as "U", "D", "T" in a list and scanned it again; same logic.

Complexity
#

Time O(n), space O(n) (the nums[1:] copy).

Mistakes to Avoid
#

  • Equal neighbors are not new hills or valleys; skip them.

Interview Explanation
#

I look at the direction of each adjacent pair, skip equal ones, and remember the last non-flat direction; each change of direction adds one hill or valley. Time O(n).

Related

LeetCode 3423: Maximum Difference Between Adjacent Elements in a Circular Array
·1 min
LeetCode Easy Array
LeetCode 3423 note: circular adjacency includes the last and first elements; starting from i = 0 with nums[i - 1] covers it
LeetCode 3550: Smallest Index With Digit Sum Equal to Index
·1 min
LeetCode Easy Math Array
LeetCode 3550 note: check indices in increasing order, computing each digit sum; the first match is the answer
LeetCode 1979: Find Greatest Common Divisor of Array
·1 min
LeetCode Easy Math Number-Theory Gcd Array
LeetCode 1979 note: find the minimum and maximum, then take their GCD with Euclid’s algorithm
LeetCode 1920: Build Array from Permutation
·1 min
LeetCode Easy Array Simulation
LeetCode 1920 note: follow the definition ans[i] = nums[nums[i]]; for O(1) extra space, stack the new value times n on top of the old one
LeetCode 1304: Find N Unique Integers Sum up to Zero
·1 min
LeetCode Easy Math Array
LeetCode 1304 note: place 1..n/2 and their negatives so each pair cancels, adding 0 when n is odd
LeetCode 2094: Finding 3-Digit Even Numbers
·2 mins
LeetCode Easy Hash-Table Enumeration Array
LeetCode 2094 note: enumerate the even numbers 100 to 998 instead and check that each digit needed is available; Counter subtraction keeps only positives