Build prefix sums
Difficulty: Easy
Try your first run
No account is needed to try this exercise. Write your answer, run the tests, and use the feedback to improve it.
- Read the examples and the required return value.
- Edit the supplied function in the editor, keeping its name and parameters. Return your answer, then select Run code.
- Use the test feedback to try again. Hints are available without replacing your code.
Return n+1 prefix sums starting with zero; entry k sums values before index k.
Examples
[][0][2, -1, 3][0, 2, 1, 4][0, 0][0, 0, 0]Constraints
Use the stated representation and return value. Do not mutate inputs. Unless a tighter limit is stated, arrays contain at most 200 integers in -1000..1000; graphs have at most 100 vertices, valid indices and 1000 edges; tree depth is at most 30. No network or file access. Tests support learning; review the implementation to check the requested algorithm.
Review lesson: Arrays and prefix computationsA little nudge
Reveal one hint at a time. Give yourself a moment to try it.
- Write down the empty-input or smallest valid result before the general case.
- The initial zero makes empty prefixes and half-open intervals uniform.
- Trace the working state on the first example and check the stated tie/order rule.
Worked solution
Try your own approach first, then compare the reasoning.
def solve(values):
result = [0]
for value in values:
result.append(result[-1] + value)
return result
The initial zero makes empty prefixes and half-open intervals uniform.
Complexity
O(n) time and output space.
Ready when you are
Write your solution, then run it against the practice tests.
Press Esc, then Tab to leave the editor. Code runs in an isolated browser workspace. Tests support learning, not verified grading.