LeetCode 2210: Count Hills and Valleys in an Array Solution

Master LeetCode problem 2210 (Count Hills and Valleys in an Array), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2210. Count Hills and Valleys in an Array

Easy

Problem Explanation

Explanation

To solve this problem, we can iterate through the array and check each index to determine if it is part of a hill or valley. We can do this by comparing the values of the current index with its neighbors. If the neighbors are smaller, it's a hill; if they are larger, it's a valley. We need to consider edge cases where an index does not have non-equal neighbors on both sides.

  • Initialize a variable count to keep track of the number of hills and valleys.
  • Iterate through the array from index 1 to n-2.
  • For each index, check if it is part of a hill or valley based on the conditions described above.
  • Increment the count if the index is part of a hill or valley.
  • Return the final count.

Time Complexity

The time complexity of this approach is O(n) where n is the number of elements in the input array.

Space Complexity

The space complexity is O(1) as we are using a constant amount of extra space.

Solution Code

class Solution {
    public int countHillsAndValleys(int[] nums) {
        if (nums.length < 3) {
            return 0;
        }
        
        int count = 0;
        for (int i = 1; i < nums.length - 1; i++) {
            if ((nums[i] > nums[i - 1] && nums[i] > nums[i + 1]) || (nums[i] < nums[i - 1] && nums[i] < nums[i + 1])) {
                count++;
            }
        }
        
        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2210 (Count Hills and Valleys in an Array)?

This page provides optimized solutions for LeetCode problem 2210 (Count Hills and Valleys in an Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

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

The time complexity for LeetCode 2210 (Count Hills and Valleys in an Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2210 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2210 in Java, C++, or Python.

Back to LeetCode Solutions