DSA 25: Recursion - Exercises [Part 6]

More recursion examples and exercises
data structures
algorithms
Author

Tony Phung

Published

February 9, 2025

1. Staircase Problem

A staircase of N steps, and a person has the ability to climb one, two, or three steps at a time.

  • Input: Number of steps in staircase
  • Output: Unique possible paths.
def n_paths(n):
    if n<0:
        return 0
    if n==0 or n==1:
        return 1
    return n_paths(n-1) + n_paths(n-2) + n_paths(n-3)
n_paths(3)
4

2. Count Characters

  • Input: ["ab", "c", "def", "ghij"]
  • Output: 10
def count_chars(string):
    if not string:
        return 0
    return len(string[0]) + count_chars(string[1:])

count_chars(["ab", "c", "def", "ghij"])
10

3. Even-Only Array

  • Input: Any array of integers
  • Output: A new array of even values of original array
def even_only(arr):
    if not arr:
        return []
    if arr[0]%2==0:
        return [arr[0]] + even_only(arr[1:])
    return even_only(arr[1:])
even_only(arr=[1,2,3,4,5,6])
[2, 4, 6]

4. Get ‘x’ Index

  • Input: “abcdefghijklmnopqrstuvwxyz”
  • Output: 23
def get_x_idx(string):
    if string[0]=="x":
        return 0
    else:
        return get_x_idx(string[1:]) + 1
get_x_idx("abcdefghijklmnopqrstuvwxyz")
23

5. Unique Paths Problem

  • Input: number of rows & number of columns
  • Output: calculates the number of possible “shortest” paths from the upper-leftmost square to the lower-rightmost square.
def unique_paths(rows,cols):
    if rows==1 or cols==1:
        return 1
    return unique_paths(rows-1,cols)+unique_paths(rows,cols-1)
unique_paths(3,3)
6