#2210

Count Hills and Valleys in an Array

Easy
ArrayArrayTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach uses a single pass through the array to identify hills and valleys by keeping track of the last non-equal neighbor. This reduces unnecessary checks and improves efficiency.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a counter for hills and valleys and a variable to track the last non-equal value.
  2. 2Step 2: Iterate through the array, checking for hills and valleys only when the current value is different from the last non-equal value.
  3. 3Step 3: Update the last non-equal value as you go.
  4. 4Step 4: Return the counter.
solution.py18 lines
1def countHillsAndValleys(nums):
2    count = 0
3    n = len(nums)
4    last_non_equal = None
5    for i in range(1, n - 1):
6        if nums[i] != last_non_equal:
7            left, right = i - 1, i + 1
8            while left >= 0 and nums[left] == nums[i]:
9                left -= 1
10            while right < n and nums[right] == nums[i]:
11                right += 1
12            if left >= 0 and right < n:
13                if nums[left] < nums[i] > nums[right]:
14                    count += 1
15                elif nums[left] > nums[i] < nums[right]:
16                    count += 1
17            last_non_equal = nums[i]
18    return count

Complexity note: The time complexity is O(n) because we only make a single pass through the array, checking each index once. The space complexity is O(1) as we use a constant amount of extra space.

  • 1Identifying the closest non-equal neighbors is crucial for determining hills and valleys.
  • 2Adjacent indices with the same value should be treated as part of the same hill or valley.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.