Peak and Pride



Let's call an array A a mountain if the following properties hold:
  • A.length >= 3
  • There exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]
Given an array that is definitely a mountain, return any i such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1].
Example 1:
Input: [0,1,0]
Output: 1
Example 2:
Input: [0,2,1,0]
Output: 1

If you play close attention to the problem, it actually ends up being much simpler than the whole problem statement suggests. Since the input is confirmed to be a mountain (hence you don’t need to check whether it is a mountain or not), then all you really need is to find the max element in the array! Now even if the question was to determine whether the input was a mountain or not, you could still find the max and then do an O(n) to determine whether that max is the peak of the mountain or not. Code is below.

Below you’ll also find a screenshot of our Pride Month experience (click here to check it out: www.bing.com and type “pride mon”). This is a tiny way to celebrate diversity, inclusion and equality during these times when these values are not being properly celebrated by many of our politicians. Cheers, Marcelo.





public class Solution
{
public int PeakIndexInMountainArray(int[] A)
{
int max = Int32.MinValue;
int maxIndex = -1;
for (int i = 0; i < A.Length; i++)
{
if (A[i] > max)
{
max = A[i];
maxIndex = i;
}
}
return maxIndex;
}
}

Comments

  1. Nice simple solution. Although, I think you can do a binary search to find the max element to solve it in O(log n). :-)

    Reply Delete
    Replies
    1. Yeah thinking about it more and knowing that the mountain property is guaranteed, I think you’re right!

      Delete
  2. An excellent observation, Marcelo! The C++ implementation of this idea is, as always, more concise than C# :P and looks like:

    class Solution {
    public:
    int peakIndexInMountainArray(const vector& A) {
    return distance(A.cbegin(), max_element(A.cbegin(), A.cend()));
    }
    };

    but a slightly more verbose implementation below takes advantage of another observation - for a given index i if an element to its left is greater or equal to it, a peak could only be on its left (i-1 or further to its left), if an element to its right is less than or equal to it, a peak could only be on its right (i+1 or further to its right) and otherwise A[i-1] < A[i] > A[i+1] and we have found the peak. The code is:

    class Solution {
    public:
    int peakIndexInMountainArray(const vector& A) {
    int left = 1;
    int right = A.size() - 2;
    while (left <= right) {
    int mid = left + (right - left) / 2;
    if (A[mid-1] >= A[mid]) {
    right = mid - 1;
    } else if (A[mid] <= A[mid+1]) {
    left = mid + 1;
    } else {
    return mid;
    }
    }
    return -1;
    }
    };

    https://leetcode.com/problems/peak-index-in-a-mountain-array/discuss/141301/log(N)-solution-based-on-binary-search-in-C++.

    Cheers,
    Taras

    Reply Delete

Post a Comment

[フレーム]

Popular posts from this blog

Quasi FSM (Finite State Machine) problem + Vibe

Not really an FSM problem since the state isn't changing, it is just defined by the current input. Simply following the instructions should do it. Using VSCode IDE you can also engage the help of Cline or Copilot for a combo of coding and vibe coding, see below screenshot. Cheers, ACC. Process String with Special Operations I - LeetCode You are given a string  s  consisting of lowercase English letters and the special characters:  * ,  # , and  % . Build a new string  result  by processing  s  according to the following rules from left to right: If the letter is a  lowercase  English letter append it to  result . A  '*'   removes  the last character from  result , if it exists. A  '#'   duplicates  the current  result  and  appends  it to itself. A  '%'   reverses  the current  result . Return the final string  result  after processing all char...

Shortest Bridge – A BFS Story (with a Twist)

Here's another one from the Google 30 Days challenge on LeetCode — 934. Shortest Bridge . The goal? Given a 2D binary grid where two islands (groups of 1s) are separated by water (0s), flip the fewest number of 0s to 1s to connect them. Easy to describe. Sneaky to implement well. 🧭 My Approach My solution follows a two-phase Breadth-First Search (BFS) strategy: Find and mark one island : I start by scanning the grid until I find the first 1 , then use BFS to mark all connected land cells as 2 . I store their positions for later use. Bridge-building BFS : For each cell in the marked island, I run a BFS looking for the second island. Each BFS stops as soon as it hits a cell with value 1 . The minimum distance across all these searches gives the shortest bridge. πŸ” Code Snippet Here's the core logic simplified: public int ShortestBridge(int[][] grid) { // 1. Mark one island as '2' and gather its coordinates List<int> island = FindAndMark...

Classic Dynamic Programming IX

A bit of vibe code together with OpenAI O3. I asked O3 to just generate the sieve due to laziness. Sieve is used to calculate the first M primes (when I was using Miller-Rabin, was giving me TLE). The DP follows from that in a straightforward way: calculate the numbers from i..n-1, then n follows by calculating the min over all M primes. Notice that I made use of Goldbach's Conjecture as a way to optimize the code too. Goldbach's Conjecture estates that any even number greater than 2 is the sum of 2 primes. The conjecture is applied in the highlighted line. Cheers, ACC. PS: the prompt for the sieve was the following, again using Open AI O3 Advanced Reasoning: " give me a sieve to find the first M prime numbers in C#. The code should produce a List<int> with the first M primes " Minimum Number of Primes to Sum to Target - LeetCode You are given two integers  n  and  m . You have to select a multiset of  prime numbers  from the  first   m  pri...