Count Peaks and Valleys
Updated
Problem statement
You are given an integer array nums. Neighbouring elements with the same value form one flat run, and a whole run is treated as a single point.
A run is a peak when the nearest different value on its left and the nearest different value on its right are both smaller than it. It is a valley when both are larger. A run that touches the start or the end of the array has no different value on that side, so it is never a peak or a valley.
Return the number of peaks plus the number of valleys.
Function
countPeaksAndValleys(nums: int[]) → intExamples
Example 1
nums = [1,3,3,2,5,5,5,4]return = 3- Joining equal neighbours gives the runs
1, 3, 2, 5, 4. - The run of
3s has1and2beside it, both smaller: a peak.2has3and5beside it, both larger: a valley. - The run of
5s has2and4beside it, both smaller: a peak. The runs at the two ends do not count, so the answer is3.
Example 2
nums = [4,4,3,2,2,1]return = 0- The runs are
4, 3, 2, 1, which only go down. - No run has smaller values on both sides or larger values on both sides, so the answer is
0.
Example 3
nums = [5,1,5,1,5]return = 3- The values go down and up in turn, like a wiggle-sorted array.
- Indices 1, 2 and 3 are a valley, a peak and a valley; the end values do not count. The answer is
3.
Constraints
1 <= nums.length <= 1000001 <= nums[i] <= 1000000000
More IBM Online Assessment questions
- Missing IntervalsOA · Seen Nov 2026
- Last Object Exit TimeOA · Seen Nov 2026
- Count Strictly Increasing Contiguous WindowsOA · Seen Nov 2026
- Total Each Letter's Count in an Encoded StringOA · Seen Nov 2026
- Count Servers With No Requests in a Time WindowOA · Seen Nov 2026
- Maximum Easy Tasks After RearrangingOA · Seen Nov 2026
- Tree Pythagorean TriplesOA · Seen Oct 2026
- Minimum Power-of-Two Removal OperationsOA · Seen Oct 2026
- Maximum Compatible Time WindowsOA · Seen Oct 2026
- Query Type Frequency WindowOA · Seen Oct 2026
Similar questions at other companies
- Total Cost Against the Lowest Earlier PricePayPal · OAPayPal interview questions
- Count User Mentions in Chat MessagesRamp · OARamp interview questions
- Count Valid Square PairsAuxoAI · OA
- Catch Fish with Reusable BaitsSusquehanna International Group (SIG) · OASusquehanna International Group (SIG) interview questions
- Two SumAmazon · OA · PHONE SCREEN
- Find Words That Can Be Formed by CharactersTabaPay · OA
- Server InvestmentRippling · OARippling interview questions
- Book Reading EveningsGoogle · OAGoogle interview questions
- Minimum Index Distance Between Person and CakeSnowflake · OA · PHONE SCREENSnowflake interview questions
- Basic Item DiscountsPalantir · OAPalantir interview questions