Recursion on Arrays and Strings in DSA Python - Time & Space Complexity
When we use recursion on arrays or strings, we call the same function repeatedly on smaller parts.
We want to know how the number of these calls grows as the input gets bigger.
Analyze the time complexity of the following code snippet.
def sum_array(arr, n):
if n == 0:
return 0
return arr[n-1] + sum_array(arr, n-1)
This function adds all elements of an array by calling itself on smaller parts until it reaches the start.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive call reducing the problem size by 1 each time.
- How many times: The function calls itself once for each element, so n times.
Each new element adds one more recursive call, so the total calls grow directly with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls |
| 100 | 100 calls |
| 1000 | 1000 calls |
Pattern observation: The number of calls grows linearly as input size increases.
Time Complexity: O(n)
This means the time taken grows in direct proportion to the size of the array or string.
[X] Wrong: "Recursion always makes the code slower exponentially."
[OK] Correct: Here, recursion calls happen once per element, so it grows linearly, not exponentially.
Understanding how recursion scales helps you explain your solutions clearly and choose the best approach during interviews.
"What if the recursion called itself twice for each element (like in some tree problems)? How would the time complexity change?"
Practice
Solution
Step 1: Understand recursion basics
A recursive function calls itself with a smaller input to solve a problem step-by-step.Step 2: Apply to arrays or strings
For arrays or strings, recursion processes smaller parts until it reaches a base case (like empty array or string).Final Answer:
It calls itself with a smaller part of the array or string until a base case is reached. -> Option CQuick Check:
Recursion = smaller input calls [OK]
- Thinking recursion processes entire array at once
- Confusing recursion with loops
- Ignoring the base case
s?Solution
Step 1: Identify base case for recursion
The base case stops recursion. For strings, empty string means no more characters to reverse.Step 2: Check options
if len(s) == 0: return s checks if string length is zero and returns it, which is correct base case.Final Answer:
if len(s) == 0: return s -> Option DQuick Check:
Base case = empty string check [OK]
- Using wrong condition for base case
- Checking reversed string equality as base case
- Returning input without base case
def sum_array(arr):
if len(arr) == 0:
return 0
return arr[0] + sum_array(arr[1:])
print(sum_array([1, 2, 3, 4]))Solution
Step 1: Understand recursion on array sum
Function adds first element to sum of rest of array recursively until empty array returns 0.Step 2: Calculate sum step-by-step
sum_array([1,2,3,4]) = 1 + sum_array([2,3,4]) = 1 + 2 + sum_array([3,4]) = 1 + 2 + 3 + sum_array([4]) = 1 + 2 + 3 + 4 + sum_array([]) = 1+2+3+4+0 = 10Final Answer:
10 -> Option BQuick Check:
Sum of [1,2,3,4] = 10 [OK]
- Concatenating numbers instead of adding
- Forgetting base case returns 0
- Misunderstanding slicing arr[1:]
def is_palindrome(s):
if len(s) <= 1:
return True
if s[0] != s[-1]:
return False
return is_palindrome(s[1:-1])
print(is_palindrome('racecar'))Solution
Step 1: Analyze base case and recursion
Base case checks if string length is 1 or 0, which is correct for palindrome check.Step 2: Check slicing and comparison
Slicing s[1:-1] removes first and last characters correctly. Comparison s[0] != s[-1] correctly detects mismatch.Final Answer:
The slicing s[1:-1] is correct and no error exists -> Option AQuick Check:
Correct base case and slicing = no error [OK]
- Thinking base case must be only empty string
- Assuming slicing causes infinite recursion
- Misreading character comparison
Solution
Step 1: Understand recursive filtering
Recursion should process one element and decide to include it or not, then recurse on the rest.Step 2: Apply to strings starting with 'a'
If first string starts with 'a', include it in result list plus recursive call on rest; else skip it and recurse on rest.Final Answer:
Check first string; if it starts with 'a', include it and recurse on rest; else recurse on rest without including it. -> Option AQuick Check:
Recursive filter = check first + recurse rest [OK]
- Using loops instead of recursion
- Ignoring elements except last
- Returning unfiltered list
Ready to prove it?
Pass the test and this pattern moves unknown
