BackeasyArraysCognizant

Calculating Total Points Scored by a Team in a Series of Matches Solution

Problem Statement

You are given an integer array scores of length n and two zero‑based indices l and r with 0 ≤ l ≤ r < n. Compute the sum of all elements from scores[l] to scores[r] inclusive. The input consists of three lines: the first line contains n, the second line contains n space‑separated integers representing scores, and the third line contains the two indices l and r. Output a single integer – the required sum.

Example 1
Input
5 3 7 2 9 4 1 3
Output
18

Explanation: The sub‑array defined by indices 1 to 3 is [7,2,9]. Adding them yields 7+2+9=18.

Example 2
Input
6 -5 10 0 -2 8 3 0 5
Output
14

Explanation: All elements are included: -5+10+0-2+8+3=14.

Example 3
Input
4 1000000000 1000000000 1000000000 1000000000 2 3
Output
2000000000

Explanation: Indices 2 and 3 cover the last two numbers, each 1,000,000,000. Their sum is 2,000,000,000.

Constraints

  • 1 <= n <= 100000
  • -10^9 <= scores[i] <= 10^9
  • 0 <= l <= r < n
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Calculating Total Points Scored by a Team in a Series of Matches — Problem Statement & Solution Guide

ArraysEasyPrefix Sum
TimeO(n)
|
SpaceO(n)

Problem Description

You are given an integer array scores of length n and two zero‑based indices l and r with 0 ≤ l ≤ r < n. Compute the sum of all elements from scores[l] to scores[r] inclusive. The input consists of three lines: the first line contains n, the second line contains n space‑separated integers representing scores, and the third line contains the two indices l and r. Output a single integer – the required sum.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Calculating Total Points Scored by a Team in a Series of Matches"

easy

WHY DOES IT MATTER?

Range‑sum queries appear in analytics, finance, and gaming where you frequently need totals over sliding windows; mastering prefix sums gives you a constant‑time answer after linear preprocessing.

OPTIMIZATION CHALLENGE

The insight is to store partial aggregates once (the prefix array) instead of recomputing them for every query, turning repeated O(k) scans into O(1) look‑ups.

REAL-WORLD CONNECTION

Think of a bank ledger where each entry records daily profit; the cumulative balance at day i is the prefix sum, and the profit between days l and r is just the difference of two balances—mirroring how distributed systems compute aggregates from checkpoints.

When coding, first read the whole array, build the prefix array in a single pass, and then answer the query with a one‑liner; this avoids off‑by‑one errors and keeps the code clean.

COMPLEXITY AT A GLANCE

⏱ Time:O(n)
💾 Space:O(n)

Core Theory — Why This Approach?

The task of summing a sub‑array is a classic example of range query problems. A naïve solution scans the segment from index l to r for each query, leading to O(r‑l+1) time per query, which becomes prohibitive when the array is large or when many queries are asked. The optimal paradigm uses a prefix‑sum (cumulative‑sum) array: prefix[i] stores the sum of the first i elements, allowing any range sum to be answered in O(1) by computing prefix[r+1]‑prefix[l]. Building the prefix array itself costs O(n) time and O(n) extra space, but it amortises the cost across all queries, turning a potentially quadratic workload into linear preprocessing followed by constant‑time answers.

Interview Questions on This Problem

Q1How would you modify your solution if you had to answer Q = 10⁵ range‑sum queries on the same array?

Pre‑compute a prefix‑sum array in O(n) time; each query then returns prefix[r+1]‑prefix[l] in O(1), giving overall O(n+Q) time and O(n) space.

Q2What data structure can answer dynamic range‑sum queries where the array elements may change?

A Binary Indexed Tree (Fenwick) or a Segment Tree supports point updates and range‑sum queries in O(log n) time each.

Q3Why might using a 32‑bit integer for the cumulative sum cause bugs, and how do you prevent it?

If the sum exceeds 2³¹‑1 it overflows; using a 64‑bit type (long long in C++, long in Java, int64 in Go) safely accommodates the maximum possible sum.

Examples

Example 1

Input

5
3 7 2 9 4
1 3

Output

18

Explanation: The sub‑array defined by indices 1 to 3 is [7,2,9]. Adding them yields 7+2+9=18.

Example 2

Input

6
-5 10 0 -2 8 3
0 5

Output

14

Explanation: All elements are included: -5+10+0-2+8+3=14.

Example 3

Input

4
1000000000 1000000000 1000000000 1000000000
2 3

Output

2000000000

Explanation: Indices 2 and 3 cover the last two numbers, each 1,000,000,000. Their sum is 2,000,000,000.

Constraints

  • 1 <= n <= 100000
  • -10^9 <= scores[i] <= 10^9
  • 0 <= l <= r < n

Optimal Approach & Strategy

Build a prefix‑sum array in one pass (O(n)), then compute the answer as prefix[r+1]‑prefix[l] in O(1).

Brute Force Approach

Loop from l to r, adding each element to an accumulator; this directly follows the problem statement but costs O(r‑l+1) time.

Verified Code Solutions

JavaScript Solution
Time: O(n)
function rangeSum(scores, l, r) {
    let sum = 0;
    for(let i=l;i<=r;i++) sum += scores[i];
    return sum;
}
function main(){
    const fs = require('fs');
    const data = fs.readFileSync(0,'utf8').trim().split(/\s+/).map(Number);
    if(data.length===0) return;
    let idx=0;
    const n=data[idx++];
    const scores=data.slice(idx, idx+n); idx+=n;
    const l=data[idx++];
    const r=data[idx++];
    console.log(rangeSum(scores,l,r));
}
main();

Asked in Top Tech Interviews

Cognizant

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.