Introduction

When working with arrays, one common problem is calculating the mean (average) of elements within a given range. If we process multiple queries on the same array, a naive approach can become inefficient.

In this article, we’ll explore how to efficiently compute the mean of subarray ranges using the Prefix Sum technique, reducing time complexity significantly.

Problem Statement

Given:

For each query:

Example

Input:

Output:

Explanation:

Naive Approach (Inefficient)

For each query:

Time Complexity: O(n × q)

This is too slow for large inputs.

Optimized Approach: Prefix Sum

What is Prefix Sum?

A prefix sum array stores cumulative sums:

prefix[i] = arr[0] + arr[1] + ... + arr[i]

Example:

How It Works

Step 1: Build Prefix Sum Array

prefix[i] = prefix[i-1] + arr[i]

Step 2: Calculate Range Sum

If l == 0:

sum = prefix[r]

Else:

sum = prefix[r] - prefix[l - 1]

Step 3: Compute Mean

mean = sum / (r - l + 1)

(Note: Integer division automatically gives the floor value in C#)

C# Implementation

using System;
using System.Collections.Generic;

public class Solution
{
    public List<int> FindMean(int[] arr, int[][] queries)
    {
        int n = arr.Length;
        List<int> result = new List<int>();

        // Step 1: Build prefix sum array
        int[] prefix = new int[n];
        prefix[0] = arr[0];

        for (int i = 1; i < n; i++)
        {
            prefix[i] = prefix[i - 1] + arr[i];
        }

        // Step 2: Process queries
        foreach (var q in queries)
        {
            int l = q[0];
            int r = q[1];
            int sum;

            if (l == 0)
            {
                sum = prefix[r];
            }
            else
            {
                sum = prefix[r] - prefix[l - 1];
            }

            int count = r - l + 1;
            int mean = sum / count; // floor value

            result.Add(mean);
        }

        return result;
    }
}

Complexity Analysis

Why Use Prefix Sum?

Conclusion

Using the Prefix Sum technique, we can efficiently solve range-based problems like finding the mean of subarrays. This approach is simple, fast, and highly scalable.

If you’re preparing for coding interviews or working on performance-critical applications, mastering this technique is essential.