EasyNo. 2210

Count Hills and Valleys in an Array — LeetCode 2210 Python Solution

Topics
Array
Reading time
3 min

The problem

You are given a 0-indexed integer array nums. An index i is part of a hill in nums if the closest non-equal neighbors of i are smaller than nums[i].

Example

Input
nums = [2,4,1,1,6,5]
Output
3
Explanation
At index 0: There is no non-equal neighbor of 2 on the left, so index 0 is neither a hill nor a valley.

Python solution

PythonSolution
class Solution:
    def countHillValley(self, nums: List[int]) -> int:
        ans = j = 0
        for i in range(1, len(nums) - 1):
            if nums[i] == nums[i + 1]:
                continue
            if nums[i] > nums[j] and nums[i] > nums[i + 1]:
                ans += 1
            if nums[i] < nums[j] and nums[i] < nums[i + 1]:
                ans += 1
            j = i
        return ans

Complexity

Time
O(n)where n is the length of the array
Space · auxiliary
O(1)

Related problems

Related problems
No.ProblemDifficulty
0057Insert IntervalMedium
0228Summary RangesEasy
0485Max Consecutive OnesEasy
0665Non-decreasing ArrayMedium
0674Longest Continuous Increasing SubsequenceEasy
0699Falling SquaresHard

Frequently asked questions

How hard is LeetCode 2210. Count Hills and Valleys in an Array?

LeetCode 2210. Count Hills and Valleys in an Array is rated Easy on LeetCode.

What is the time complexity of LeetCode 2210. Count Hills and Valleys in an Array?

The Python solution on this page runs in O(n), where n is the length of the array.

What is the space complexity of LeetCode 2210. Count Hills and Valleys in an Array?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 2210. Count Hills and Valleys in an Array cover?

LeetCode 2210. Count Hills and Valleys in an Array is tagged Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.