LearnProductTeam
Recursion
Sum Array Recursively
Omer Goldberg
December 20, 2020
5 min

Start now! 🚀🚀

Join our beta to get free access to our full syllabus 🎉 🥳

Intro

This is a warm up for the recursive problems we’ll work on later :)

In this problem we want to write a function that accepts a list of ints and returns the sum of all ints recurisvely.

Example 1

Input: [1] Output: 1

Example 2

Input: [1, 2] Output: 3

Example 3

Input: [1, 2, 3, 4] Output: 10

Example 4

Input: [] Output: 0

Breakdown

Let’s go back to our amazing basics.

Base case: What is the sum of an empty array? This is an edge case we need to handle. Let’s say 0. What is the sum of an array with 1 element? The element itself!

Recurrence Relation: f(list) = list.pop() + add(list)

Note -> .pop() will remove the last el from the list, thus making it smaller and moving us towards our base case!

Solution


Tags

#recursion#array

Omer Goldberg

Tech Lead

crafting mobile experiences @ instagram. tech Lead @ facebook. former algorithm and fullstack Teacher @ israel tech challenge. crypto crazy.

Expertise

Algorithms
System Design
Android
Blockchain

Social Media

instagramlinkedinwebsite

Related Posts
18

Generate Permutations
Generate Permutations
June 20, 2022
11 min
© 2024, All Rights Reserved.

Quick Links

HomeLearnProductInstructors

Social Media