Python 1095.py
class Solution:
def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int:
data = mountain_arr # just a shorter name
size = data.length()
# locate index of maximum value
def gradient(x):
return data.get(x) - (0 if x == size - 1 else data.get(x + 1))
high = bisect_left(range(size), 0, key = gradient)
# basic binary search on left side
pos = bisect_left(range(high), target, key = lambda x : data.get(x))
if pos < high and data.get(pos) == target:
return pos
# reverse binary search on right side
pos = high + bisect_left(range(high, size), -target, key = lambda x : -data.get(x))
if pos < size and data.get(pos) == target:
return pos
return -1
Difficulty
and has an acceptance rate of about 42% (500k+ submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
- Interactive
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the classic “search in a mountain array” problem. A mountain array is strictly increasing up to a single peak and then strictly decreasing. The algorithm first discovers the peak index, then performs a standard binary search on the ascending part and a reversed binary search on the descending part. All interactions with the hidden MountainArray interface are minimized, and the code relies on Python’s bisect_left with custom key functions to express binary search logic concisely.
Key Steps
1. Preparing a short alias and obtaining the length
data = mountain_arr # just a shorter name
size = data.length()
The alias data shortens subsequent calls, and size stores the total number of elements, which is required for boundary checks throughout the routine.
2. Defining a gradient function to locate the peak
def gradient(x):
return data.get(x) - (0 if x == size - 1 else data.get(x + 1))
high = bisect_left(range(size), 0, key=gradient)
The gradient computes the difference between an element and its right neighbor, treating the last element as having a neighbor value of zero. In a mountain array the gradient is positive on the left side of the peak, zero at the peak (when the next element is smaller), and negative on the right side. By searching for the first index where the gradient becomes non-positive, bisect_left returns the peak index high.
3. Binary search on the ascending segment
pos = bisect_left(range(high), target, key=lambda x: data.get(x))
if pos < high and data.get(pos) == target:
return pos
The left side of the peak is strictly increasing, so a normal binary search suffices. The key lambda fetches the value at each index. If the found position is within the left segment and matches the target, the index is returned immediately.
4. Reverse binary search on the descending segment
pos = high + bisect_left(range(high, size), -target, key=lambda x: -data.get(x))
if pos < size and data.get(pos) == target:
return pos
On the right side the values decrease, which is handled by searching for -target in a transformed view where each element is negated. Adding high offsets the result to the original index space. A successful match yields the target’s index.
5. Fallback when the target is absent
return -1
If neither search locates the target, the function returns -1 to indicate failure.
Edge Cases Handled
The algorithm gracefully manages several boundary conditions without explicit branching. When the target resides at the very first element, the left-side binary search operates over an empty range (range(high) where high may be zero), and the subsequent check correctly validates the match. If the target is the peak itself, the gradient function identifies the peak index, and the left-side search will locate the target because the range includes the peak index as the upper bound (exclusive). When the target lies on the descending side, the transformed search with negated values still works even if the target is the last element, because range(high, size) includes the final index. The gradient function also safely handles the last index by substituting a zero neighbor, ensuring the peak detection does not run off the array bounds.
Performance Optimizations
The code leverages Python’s built-in bisect_left which implements binary search in C, providing fast logarithmic probing while avoiding manual loop constructs. By passing custom key functions, the algorithm reuses the same binary search routine for three distinct purposes: peak detection, ascending search, and descending search. This eliminates the need for separate implementations and reduces overhead.
All accesses to the hidden MountainArray are performed through data.get(x) only when necessary. The peak detection uses a single call per examined index, and the subsequent searches each call data.get exactly once per probe. The use of range objects avoids materializing large intermediate lists, keeping memory usage minimal.
The transformation of the descending search via negation (-data.get(x)) allows the standard bisect_left to operate on an effectively increasing sequence, avoiding the need for a custom reverse binary search routine. Offsetting the result by high reuses the same index space, eliminating extra arithmetic after the search.
Overall, the solution achieves a compact, high-performance implementation that respects the constraints of the MountainArray interface while minimizing both time and space overhead.
ELI5 - Simplified Explanation
Imagine you have a row of building blocks, but they are arranged like a tiny mountain. The blocks start small, get taller and taller until they reach the pointy peak, and then they get smaller again as they go down the other side. This code is a clever helper that wants to find a specific block in that mountain pile.
First, the helper looks at the pile to figure out where the tallest block is. Think of it like scanning the mountain top to find the summit. Once the helper knows where the peak is, it splits the mountain into two parts. The first part is the side going up, and the second part is the side going down.
The helper then checks the first side of the mountain to see if the block you want is hiding there. If it finds the right block, it tells you exactly where that block is sitting. If it does not find it in the first part, it moves over to the second part of the mountain and looks very carefully there instead. By splitting the work into two sides, the helper does not have to look at every single block one by one, which makes searching through a huge pile of blocks super fast. If the helper checks everywhere and cannot find the block you asked for, it just shakes its head to let you know the block is not in the mountain.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | C++ | Java | Python | Go | Rust | TS | |||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| YuriSpiridonov | Python | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 852: Peak Index in a Mountain Array
- problem 1671: Minimum Number of Removals to Make Mountain Array
Solved On The Same Day
- problem 3178: Find the Child Who Has the Ball After K Seconds
- problem 2750: Ways to Split Array Into Good Subarrays
- problem 2762: Continuous Subarrays
- problem 2779: Maximum Beauty of an Array After Applying Operation
- problem 1293: Shortest Path in a Grid with Obstacles Elimination
- problem 2449: Minimum Number of Operations to Make Arrays Similar
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality