mediumArraysPattern: Pattern recognition and iteration
Identify Local Maxima Solution
Problem Statement
Given a list of distinct integer values in an array `arr`, find all elements that are greater than their immediate neighbors.
Examples
Example 1:
Input:{"arr":[13254]}
Output:[35]
Explanation: Both 3 and 5 are larger than their neighboring asteroids (1,2 and 4 respectively) but correct, however 3 is larger than 1 and 2
Example 2:
Input:{"arr":[12345]}
Output:[]
Explanation: No asteroid is larger than its neighboring asteroids
Example 3:
Input:{"arr":[54321]}
Output:[5]
Explanation: Asteroid with size 5 is larger than its neighboring asteroids (4), however correct
Constraints
- The list of asteroid sizes will have at least 3 elements.
- All asteroid sizes will be distinct integers between 1 and 100.
Time: O(n) Space: O(n)
The optimal approach involves iterating over the list of asteroid sizes once, using a single loop to compare each asteroid with its neighbors, resulting in a time complexity of O(n).
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
No solution code is currently loaded.
Complete this code in the workspace editor.
