Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Sum of Subarray Ranges

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2104" 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

You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray. Return the sum of all subarray ranges of nums. A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Input: nums = [1,2,3] Output: 4 Explanation: The 6 subarrays of nums are the following: [1], range = largest - smallest = 1 - 1 = 0 [2], range = 2 - 2 = 0 [3], range = 3 - 3 = 0 [1,2], range = 2 - 1 = 1 [2,3], range = 3 - 2 = 1 [1,2,3], range = 3 - 1 = 2 So the sum of all ranges is 0 + 0 + 0 + 1 + 1 + 2 = 4. Example 2: Input: nums = [1,3,3] Output: 4 Explanation: The 6 subarrays of nums are the following: [1], range = largest - smallest = 1 - 1 = 0 [3], range = 3 - 3 = 0 [3], range = 3 - 3 = 0 [1,3], range = 3 - 1 = 2 [3,3], range = 3 - 3 = 0 [1,3,3], range = 3 - 1 = 2 So the sum of all ranges is 0 + 0 + 0 + 2 + 0 + 2 = 4. Example 3: Input: nums = [4,-2,-3,4,1] Output: 59 Explanation: The sum of all subarray ranges of nums is 59. Constraints: 1 <= nums.length <= 1000 -109 <= nums[i] <= 109 Follow-up: Could you find a solution with O(n) time complexity?

Explanation

Here's a breakdown of the approach, followed by the code:

  • Monotonic Stacks: Use two monotonic stacks (one increasing and one decreasing) to efficiently find the next smaller and next larger elements for each number in the input array.
  • Contribution Calculation: For each number, determine the number of subarrays in which it is the maximum and the number of subarrays in which it is the minimum. This is based on the distances to the next smaller/larger elements.
  • Summation: Calculate the contribution of each number to the total sum of ranges (max contribution - min contribution) and sum up these contributions.

  • Runtime Complexity: O(n)

  • Storage Complexity: O(n)

Code

    def subArrayRanges(nums):
    n = len(nums)
    max_sum = 0
    min_sum = 0

    # Calculate contribution as maximum
    stack = []
    for i in range(n):
        while stack and nums[stack[-1]] < nums[i]:
            mid = stack.pop()
            left = stack[-1] if stack else -1
            right = i
            max_sum += nums[mid] * (mid - left) * (right - mid)
        stack.append(i)

    while stack:
        mid = stack.pop()
        left = stack[-1] if stack else -1
        right = n
        max_sum += nums[mid] * (mid - left) * (right - mid)

    # Calculate contribution as minimum
    stack = []
    for i in range(n):
        while stack and nums[stack[-1]] > nums[i]:
            mid = stack.pop()
            left = stack[-1] if stack else -1
            right = i
            min_sum += nums[mid] * (mid - left) * (right - mid)
        stack.append(i)

    while stack:
        mid = stack.pop()
        left = stack[-1] if stack else -1
        right = n
        min_sum += nums[mid] * (mid - left) * (right - mid)

    return max_sum - min_sum

More from this blog

C

Chatmagic blog

2894 posts