LeetCode: Valid Mountain Array Solution
FlaggingApproach
Make sure the array:
- has one peak only
- does not have any valley
- does not have flat road (2 equal adjacent elements)
Implementation
1/**2 * @param {number[]} arr3 * @return {boolean}4 */5var validMountainArray = function (arr) {6 let peakCount = 07 let valleyCount = 08 let hasFlatWay = false910 for (let i = 1; i < arr.length - 1; i++) {11 if (arr[i] === arr[i - 1] || arr[i] === arr[i + 1]) {12 hasFlatWay = true13 }14 if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) {15 peakCount++16 }17 if (arr[i] < arr[i - 1] && arr[i] < arr[i + 1]) {18 valleyCount++19 }20 }2122 return peakCount === 1 && valleyCount === 0 && !hasFlatWay23}
Comments
Loading comments...
Tags
leetcode
array
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Replace Elements with Greatest Element on Right Side
Backward iteration, create an array of right max
Previous Post
LeetCode: Check If N and Its Double Exist
Compare with the iterated elements