The Running Total
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L3
Problem
Given a list of integers, return a list where position i is the sum of input[0..i] inclusive.
Each position holds the sum of everything before it.
Example
Input:
nums = [1,2,3,4,5]
Output:
[1,3,6,10,15]
Worked solution and explanation
Why this problem exists in real interviews
This tests the prefix sum pattern, the most fundamental cumulative operation in data processing. It checks whether candidates can build a running accumulator in a single pass.
Break down the requirements
Step 1: Initialize a running sum
Start at 0.
Step 2: Add each element and store the result
For each element, add it to the running sum and append the sum to the output.
The solution
def running_total(nums):
result = []
total = 0
for num in nums:
total += num
result.append(total)
return resultCommon follow-up questions
- How would you compute the sum of any subarray in O(1) using prefix sums? (Tests `prefix[right] - prefix[left - 1]` for range sum queries.)
- What if you needed a running product instead? (Tests replacing addition with multiplication and handling zeros.)
- How does this relate to SQL window functions? (Tests `SUM(col) OVER (ORDER BY id)` as the SQL equivalent.)