Interview 150

Peak Index in a Mountain Array

Problem
LC 852
File
interview150_LC852PeakIndexInMountainArray.java
Path
pkg5leetcode/interview150/interview150_LC852PeakIndexInMountainArray.java
Package
pkg5leetcode.interview150
Command
java pkg5leetcode/interview150/interview150_LC852PeakIndexInMountainArray.java
Approach
Binary search where mid slope points uphill.
Complexity
Time O(log n), Space O(1)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/interview150/interview150_LC852PeakIndexInMountainArray.java
1package pkg5leetcode.interview150;2 3/*4 * Peak Index in a Mountain Array | LC 8525 * APPROACH: Binary search where mid slope points uphill.6 * COMPLEXITY: Time O(log n), Space O(1)7 */8public class interview150_LC852PeakIndexInMountainArray {9    static int peakIndexInMountainArray(int[] arr) {10        int lo = 0, hi = arr.length - 1;11        while (lo < hi) {12            int mid = lo + (hi - lo) / 2;13            if (arr[mid] < arr[mid + 1]) lo = mid + 1;14            else hi = mid;15        }16        return lo;17    }18 19    public static void main(String[] args) {20        check(peakIndexInMountainArray(new int[]{0, 1, 0}) == 1, "case1");21        check(peakIndexInMountainArray(new int[]{0, 2, 1, 0}) == 1, "case2");22        System.out.println("all tests passed");23    }24 25    static void check(boolean cond, String name) {26        if (!cond) throw new AssertionError("FAILED: " + name);27        System.out.println("  PASS " + name);28    }29}