EasyNo. 2210
Count Hills and Valleys in an Array — LeetCode 2210 Python Solution
- Topics
- Array
- Reading time
- 3 min
- Source
- leetcode.com
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
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 ansComplexity
- Time
- O(n)where n is the length of the array
- Space · auxiliary
- O(1)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0057 | Insert Interval | Medium |
| 0228 | Summary Ranges | Easy |
| 0485 | Max Consecutive Ones | Easy |
| 0665 | Non-decreasing Array | Medium |
| 0674 | Longest Continuous Increasing Subsequence | Easy |
| 0699 | Falling Squares | Hard |
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.