




Sponsored
Sponsored
In this approach, the task is broken into three main steps:
arr[i] > arr[i+1] and arr[i] > arr[i-1].Time Complexity: O(log n) for peak finding and 2 * O(log n) for the two binary searches.
Total: O(log n).
Space Complexity: O(1) because we use a constant amount of space.
1#include <stdio.h>
2
3// Forward declaration of the MountainArray API.
4// You don't need to implement this interface, it is provided by the problem constraints.
5struct MountainArray {
6    int (*get)(struct
This C implementation is efficient as it implements a binary search method to find the peak in O(log n) time. After finding the peak, it searches both halves of the mountain array for the target using two separate binary searches. One binary search is for the increasing part (left of the peak) with an increasing order binary search, and another one in the decreasing half (right of the peak) with a decreasing order binary search. As it is a binary search, each takes O(log n) time.
This approach involves directly accessing each element linearly until the condition is satisfied (even though this is not allowed by the problem constraints). It is less optimal and efficient compared to the above implementations, requiring traversal of the entire array.
Time Complexity: O(n) as each element could potentially be checked once.
Space Complexity: O(1) as no extra space is used except for variables.
1#include <vector>
using namespace std;
// Mockup of MountainArray, simulating interface.
class MountainArray {
public:
    int get(int index) const;
    int length() const;
};
int findInMountainArray(int target, const MountainArray &mountainArr) {
    int len = mountainArr.length();
    for (int i = 0; i < len; ++i) {
        if (mountainArr.get(i) == target) {
            return i;
        }
    }
    return -1;
}The C++ brute-force solution iterates with a loop, accessing each value one-by-one, and checking for equality with the target value. It returns the index if a match is found and -1 if the entire array is traversed without finding the target. This is straightforward but is less optimized since it calls the get function repeatedly and traverses each element.