Solving Leetcode Interviews in Seconds with AI: Range Sum Query - Immutable
Introduction
In this blog post, we will explore how to solve the LeetCode problem "303" 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 integer array nums, handle multiple queries of the following type: Calculate the sum of the elements of nums between indices left and right inclusive where left <= right. Implement the NumArray class: NumArray(int[] nums) Initializes the object with the integer array nums. int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]). Example 1: Input ["NumArray", "sumRange", "sumRange", "sumRange"] [[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]] Output [null, 1, -1, -3] Explanation NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]); numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3 Constraints: 1 <= nums.length <= 104 -105 <= nums[i] <= 105 0 <= left <= right < nums.length At most 104 calls will be made to sumRange.
Explanation
Here's the solution:
- Prefix Sum: Calculate and store the prefix sum of the input array. This allows us to compute the sum of any range in O(1) time.
- Initialization: The
NumArrayconstructor calculates the prefix sum array. Range Sum Calculation:
sumRange(left, right)calculates the sum of the range[left, right]using the prefix sum array in constant time.Runtime Complexity: Initialization: O(n),
sumRange: O(1) Storage Complexity: O(n)
Code
class NumArray:
def __init__(self, nums: list[int]):
"""
Initializes the NumArray object with the given integer array nums.
"""
self.prefix_sums = [0] * (len(nums) + 1)
for i in range(len(nums)):
self.prefix_sums[i + 1] = self.prefix_sums[i] + nums[i]
def sumRange(self, left: int, right: int) -> int:
"""
Calculates the sum of the elements of nums between indices left and right inclusive.
"""
return self.prefix_sums[right + 1] - self.prefix_sums[left]
# Your NumArray object will be instantiated and called as such:
# nums = [-2, 0, 3, -5, 2, -1]
# obj = NumArray(nums)
# param_1 = obj.sumRange(0, 2)
# print(param_1)
# param_2 = obj.sumRange(2, 5)
# print(param_2)
# param_3 = obj.sumRange(0, 5)
# print(param_3)