Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Non-decreasing Array

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "665" 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 nums with n integers, your task is to check if it could become non-decreasing by modifying at most one element. We define an array is non-decreasing if nums[i] <= nums[i + 1] holds for every i (0-based) such that (0 <= i <= n - 2). Example 1: Input: nums = [4,2,3] Output: true Explanation: You could modify the first 4 to 1 to get a non-decreasing array. Example 2: Input: nums = [4,2,1] Output: false Explanation: You cannot get a non-decreasing array by modifying at most one element. Constraints: n == nums.length 1 <= n <= 104 -105 <= nums[i] <= 105

Explanation

Here's a breakdown of the solution:

  • Identify Inversions: Iterate through the array, looking for violations of the non-decreasing property (i.e., nums[i] > nums[i+1]).
  • Handle at Most One Inversion: If more than one inversion is found, it's impossible to make the array non-decreasing with only one modification.
  • Resolve the Inversion: When an inversion is found, try two possible modifications: either change nums[i] to nums[i+1] or change nums[i+1] to nums[i]. Choose the modification that results in a non-decreasing sequence in the local vicinity of the inversion. Special care is needed for edge cases at the beginning of the array.

  • Runtime Complexity: O(n), Storage Complexity: O(1)

Code

    def checkPossibility(nums):
    """
    Checks if an array can become non-decreasing by modifying at most one element.

    Args:
        nums: A list of integers.

    Returns:
        True if the array can become non-decreasing with at most one modification, False otherwise.
    """
    n = len(nums)
    count = 0  # Number of modifications made
    for i in range(n - 1):
        if nums[i] > nums[i + 1]:
            count += 1
            if count > 1:
                return False
            if i > 0 and nums[i + 1] < nums[i - 1]:
                nums[i + 1] = nums[i]
            else:
                nums[i] = nums[i + 1]
    return True

More from this blog

C

Chatmagic blog

2894 posts