Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Valid Mountain Array

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "941" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

Given an array of integers arr, return true if and only if it is a valid mountain array. Recall that arr is a mountain array if and only if: arr.length >= 3 There exists some i with 0 < i < arr.length - 1 such that: arr[0] < arr[1] < ... < arr[i - 1] < arr[i] arr[i] > arr[i + 1] > ... > arr[arr.length - 1] Example 1: Input: arr = [2,1] Output: false Example 2: Input: arr = [3,5,5] Output: false Example 3: Input: arr = [0,3,2,1] Output: true Constraints: 1 <= arr.length <= 104 0 <= arr[i] <= 104

Explanation

Here's a breakdown of the solution:

  • Two-Pointer Approach: Use two pointers, left and right, starting from the beginning and end of the array, respectively.
  • Ascending Phase: Increment left as long as the array elements are strictly increasing from the left.
  • Descending Phase: Decrement right as long as the array elements are strictly increasing from the right (effectively descending from the end).

  • Runtime Complexity: O(n), where n is the length of the array. Storage Complexity: O(1).

Code

    def validMountainArray(arr: list[int]) -> bool:
    """
    Given an array of integers arr, return true if and only if it is a valid mountain array.
    """
    n = len(arr)
    if n < 3:
        return False

    left = 0
    while left + 1 < n and arr[left] < arr[left + 1]:
        left += 1

    if left == 0 or left == n - 1:
        return False

    right = n - 1
    while right - 1 >= 0 and arr[right] < arr[right - 1]:
        right -= 1

    return left == right

More from this blog

C

Chatmagic blog

2894 posts