Swift Coding Test Course, Interval Sum

Problem Description

Given an integer array nums and two integers start and end, this is a problem to calculate the value of nums[start] + nums[start + 1] + ... + nums[end]. We will explore methods to efficiently calculate the range sum and how to solve this problem in Swift.

Input Example

[1, 2, 3, 4, 5], start = 1, end = 3

Output Example

9

Approach to the Problem

To solve this problem, we need to consider how to perform range addition efficiently. A simple way is to use a for loop to calculate the sum over the given index range. However, there is much room for improvement with this approach.

1. Sum Calculation Using Simple Loop

First, let’s take a look at the most basic method. This involves using a loop to calculate the sum for the given range. Below is the Swift code implementing this method.

func rangeSum(nums: [Int], start: Int, end: Int) -> Int {
        var sum = 0
        for i in start...end {
            sum += nums[i]
        }
        return sum
    }

Usage Example

let nums = [1, 2, 3, 4, 5]
let result = rangeSum(nums: nums, start: 1, end: 3)
print(result) // 9

2. Approach Using Cumulative Sum Array

A simple loop can lead to performance degradation in certain cases. Particularly, if we need to calculate the range sum multiple times for a large array, executing a loop each time is inefficient. In such cases, using a cumulative sum array is an effective approach.

By using a cumulative sum array, we can calculate the sum of a specific range of the array in constant time O(1). The approach is as follows:

  1. Create a cumulative sum array of the same size as the input array.
  2. Add the cumulative sum of the previous index to each index of the cumulative sum array.
  3. To calculate the range sum, we can easily compute it using prefixSum[end + 1] - prefixSum[start].

Cumulative Sum Array Implementation Code

func rangeSumUsingPrefix(nums: [Int], start: Int, end: Int) -> Int {
        var prefixSum = [0]    // Initialize cumulative sum array
        prefixSum.append(0)    // Initialize the first index to 0
        
        // Generate cumulative sum array
        for num in nums {
            prefixSum.append(prefixSum.last! + num)
        }
        
        // Calculate range sum
        return prefixSum[end + 1] - prefixSum[start]
    }

Usage Example

let nums = [1, 2, 3, 4, 5]
let result = rangeSumUsingPrefix(nums: nums, start: 1, end: 3)
print(result) // 9

Case Analysis

In this lecture, we have examined two approaches to solve the range sum problem. The method using a simple loop is intuitive and easy to understand, but can lead to performance degradation for large arrays. On the other hand, the method utilizing cumulative sum arrays is superior in terms of performance.

Conclusion

The range sum problem is a great example of utilizing algorithms and data structures. We learned that efficient approaches can lead to quicker solutions to problems. Try solving such problems using Swift and familiarize yourself with various algorithmic techniques.

References