avatarNaina Chaturvedi

Summary

The provided web content outlines a comprehensive guide on recursion within the context of data structures, algorithms, and system design, emphasizing its importance and offering solutions to common recursion problems with a focus on tree traversal and system design case studies.

Abstract

The web content titled "Day 9 of 30 days of Data Structures and Algorithms and System Design Simplified — Recursion" delves into the concept of recursion, explaining its definition, advantages, and patterns. It underscores the significance of recursion in problem-solving and its prevalence in technical interviews. The article covers key recursion problems such as inverting a binary tree, flip equivalent binary trees, binary tree inorder traversal, and maximum depth of a binary tree, providing detailed solutions and patterns to approach these problems. Additionally, it introduces a series of system design case studies, including the design of popular applications like Instagram and Twitter, and offers resources for further learning in data structures, algorithms, and machine learning projects. The content also promotes a YouTube channel, Ignito, for video explanations and encourages readers to subscribe for updates and more in-depth learning.

Opinions

  • The author believes recursion to be a highly important concept in computer science, particularly for those preparing for technical interviews.
  • The article suggests that recursion simplifies the coding process by making solutions more readable and concise.
  • It is implied that understanding recursion is crucial for tackling problems related to tree data structures effectively.
  • The author emphasizes the importance of defining a base case in recursive functions to prevent infinite loops.
  • The content promotes a hands-on approach to learning, encouraging readers to implement solutions to fully grasp recursion.
  • The author values the community aspect of learning, suggesting that readers engage through comments and subscriptions to enhance their understanding.
  • There is an emphasis on the practical application of recursion, with the inclusion of real-world system design case studies.
  • The article advocates for the use of additional resources, such as video explanations and newsletters, to complement text-based learning.

Day 9 of 30 days of Data Structures and Algorithms and System Design Simplified — Recursion

Pic credits : flickr

Welcome back peeps. Hope all’s well. In this post we will cover Recursion as follows —

What and Why Recursion(in 2–3 sentences)?

How does Recursion work?

Important Patterns and Techniques in Recursion Questions

Most Important Questions with Solutions

Complexity Analysis

Tips and Techniques to solve Recursion Questions Fast.

Projects Videos —

All the projects, data structures, SQL, algorithms, system design, Data Science and ML , Data Analytics, Data Engineering, , Implemented Data Science and ML projects, Implemented Data Engineering Projects, Implemented Deep Learning Projects, Implemented Machine Learning Ops Projects, Implemented Time Series Analysis and Forecasting Projects, Implemented Applied Machine Learning Projects, Implemented Tensorflow and Keras Projects, Implemented PyTorch Projects, Implemented Scikit Learn Projects, Implemented Big Data Projects, Implemented Cloud Machine Learning Projects, Implemented Neural Networks Projects, Implemented OpenCV Projects,Complete ML Research Papers Summarized, Implemented Data Analytics projects, Implemented Data Visualization Projects, Implemented Data Mining Projects, Implemented Natural Leaning Processing Projects, MLOps and Deep Learning, Applied Machine Learning with Projects Series, PyTorch with Projects Series, Tensorflow and Keras with Projects Series, Scikit Learn Series with Projects, Time Series Analysis and Forecasting with Projects Series, ML System Design Case Studies Series videos will be published on our youtube channel ( just launched).

Subscribe today!

System Design Case Studies — In Depth

Design Instagram

Design Messenger App

Design Twitter

Design URL Shortener

Design Dropbox

Design Youtube

Design API Rate Limiter

Design Web Crawler

Design Facebook’s Newsfeed

Design Yelp

Design Uber

Design Tinder

Design Tiktok

Design Whatsapp

Most Popular System Design Questions

Mega Compilation : Solved System Design Case studies

Recursion

Importance : Very High

Day 2 of data structures and algorithms covers the topics that are most important and with highest ROI.

Note : New Recursion with solutions will be added everyday. So keep checking this post daily.

Let’s dive in!

What is Recursion?

Recursion is a technique in which the program/function calls itself.

It has many advantages over the iterative solutions, for e.g its easier to read and write ( and visualize) and minimize the length of the code.

Examples of Recursion problems —

Max depth of a tree

Diameter of a tree

Invert a tree

Flip a tree

Inorder/Preorder/Postorder Tree Traversals

Depth first search in Graphs

Factorial of a number

Tower of Hanoi etc

How does Recursion work?

Recursion is a programming technique where a function calls itself in order to solve a problem. It is used when a problem can be broken down into smaller, identical subproblems.

In recursion, a base case is defined to stop the recursive function calls and prevent infinite looping. The function then calls itself with a modified set of inputs, typically by reducing the size of the problem, until the base case is reached and the function can return a result.

The main gist is — when recursing, the machine remembers previous state of the problem and the information is held in the activation stack.

All the functions that are made recursive have —

  1. Base Case ( Termination condition)
  2. Recursive Call (function calls itself)
def func_name(): 
        Recursive call to function func()
    func_name()

Recursion terminates when it meets/satisfies the base case. It uses extra space in the stack memory.

Important Patterns and Techniques in Recursion Questions

Important patterns and techniques in recursion questions include identifying the base case, understanding how the function calls itself with modified inputs, and recognizing when recursion is an appropriate solution to the problem.

Recursion function solves a problem by calling a copy of itself and dividing and solving smaller subproblems of the original problem recursively .

Patterns → Questions like below belong to Recursion ( not limited to):

Inorder/Preorder/Postorder Tree Traversals

Depth first search in Graphs

Factorial of a number

Tower of Hanoi etc

Most Important Questions with Solutions

Note : New Recursion questions with solutions are added every day. So keep checking this post daily.

Golden rule is — Learn by doing/implementing

In this we will see most important Recursion questions.

Invert Binary Tree

Question —

Given the root of a binary tree, invert the tree, and return its root.

Example :

Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

Solution :

Main Logic/Idea —

The main logic — to invert left tree ( by calling invertTree function recursively) on the left tree. Invert right tree( by calling invertTree function recursively) on the right tree. Assign the right to left and vice versa.

Main Logic

Implementation —

def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root:
            return None
        
        temp = root.left
        root.left = root.right
        root.right = temp
        
        self.invertTree(root.left)
        self.invertTree(root.right)
        return root

Question Link

Similar Pattern —

Reverse Odd Levels of Binary Tree

Full Code Video Explanation ( In progress. Subscribe today for updates) :

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

Flip Equivalent Binary Trees

Question —

For a binary tree T, we can define a flip operation as follows: choose any node, and swap the left and right child subtrees.

A binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y after some number of flip operations.

Given the roots of two binary trees root1 and root2, return true if the two trees are flip equivalent or false otherwise.

Example :

Input: root1 = [1,2,3,4,5,6,null,null,null,7,8], root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7]
Output: true

Solution :

Main Logic/Idea —

The main gist is — Flip the left and right subtree, flip the roots ( right and left) recursively. If the trees node/root value is not equal then return False.

Main Logic

Implementation —

def flipEquiv(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
        if not root1 or not root2:
            return not root1 and not root2
        
        if root1.val != root2.val:
            return False
        
        ans = (self.flipEquiv(root1.left,root2.left) and self.flipEquiv(root1.right,root2.right)) or (self.flipEquiv(root1.left,root2.right) and self.flipEquiv(root1.right,root2.left))
        
        return ans

Question Link

Similar Pattern —

Smallest String Starting From Leaf

Binary Tree Coloring Game

Delete Leaves With a Given Value

Full Code Video Explanation ( In progress. Subscribe today for updates) :

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

Binary Tree Inorder Traversal

Question —

Given the root of a binary tree, return the inorder traversal of its nodes' values.

Example:

Input: root = [1,null,2,3]
Output: [1,3,2]

Solution :

Main Logic/Idea —

The main logic is to follow Inorder traversal rule — Left, Root, Right.

So first traverse the left subtree, then root and then right subtree.

Main Logic

Implementation —

def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        ans = []
        
        def ino(root):
            if not root:
                return
            ino(root.left)
            ans.append(root.val)
            ino(root.right)
        ino(root)
        return ans

Question Link

Similar Pattern —

Inorder Successor in BST

Convert Binary Search Tree to Sorted Doubly Linked List

Minimum Distance Between BST Nodes

Closest Binary Search Tree Value II

Full Code Video Explanation ( In progress. Subscribe today for updates) :

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

Maximum Depth of Binary Tree

Question —

Given the root of a binary tree, return its maximum depth.

A binary tree’s maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Example :

Input: root = [3,9,20,null,null,15,7]
Output: 3

Solution :

Main Logic/Idea —

The main idea is to calculate the depth of left subtree and right subtree and then choose whichever is max ( add 1 to it).

Main Logic

Implementation —

def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root: return 0
        
        return 1+ max((self.maxDepth(root.left)), (self.maxDepth(root.right)))

Question Link

Similar Pattern —

Time Needed to Inform All Employees

Amount of Time for Binary Tree to Be Infected

Maximum Depth of N-ary Tree

Full Code Video Explanation ( In progress. Subscribe today for updates) :

Note : New Recursion with solutions will be added everyday. So keep checking this post daily.

Tips and Techniques to solve Recursion Questions Fast —

Remember the gist of recursion problem is that recursion function solves a problem by calling a copy of itself and dividing and solving smaller subproblems of the original problem.

Always remember to define a base case ( which is like the termination condition).

That’s it for now. Day 10 : Divide and Conquer Technique coming soon !

Let me know if you have questions in the comment section below. Subscribe/ Follow, Like/Clap as it will encourage me to write more in my free time and Stay Tuned!!

Read More —

11 most important System Design Base Concepts

1. System design basics

2. Horizontal and vertical scaling

3. Load balancing and Message queues

4. High level design and low level design, Consistent Hashing, Monolithic and Microservices architecture

5. Caching, Indexing, Proxies

6. Networking, How Browsers work, Content Network Delivery ( CDN)

7. Database Sharding, CAP Theorem, Database schema Design

8. Concurrency, API, Components + OOP + Abstraction

9. Estimation and Planning, Performance

10. Map Reduce, Patterns and Microservices

11. SQL vs NoSQL and Cloud

12. Most Popular System Design Questions

13. System Design Template — How to solve any System Design Question

14. Quick RoundUp : Solved System Design Case Studies

Some of the other best Series —

60 days of Data Science and ML Series with projects

30 Days of Natural Language Processing ( NLP) Series

30 days of Machine Learning Ops

30 days of Data Structures and Algorithms and System Design Simplified

60 Days of Deep Learning with Projects Series

30 days of Data Engineering with projects Series

Data Science and Machine Learning Research ( papers) Simplified **

100 days : Your Data Science and Machine Learning Degree Series with projects

23 Data Science Techniques You Should Know

Tech Interview Series — Curated List of coding questions

Complete System Design with most popular Questions Series

Complete Data Visualization and Pre-processing Series with projects

Complete Python Series with Projects

Complete Advanced Python Series with Projects

Kaggle Best Notebooks that will teach you the most

Complete Developers Guide to Git

Exceptional Github Repos — Part 1

Exceptional Github Repos — Part 2

All the Data Science and Machine Learning Resources

210 Machine Learning Projects

Tech Newsletter —

If you are interested, you can join my newsletter through which I send tech interview tips, techniques, patterns, hacks — Software Development, ML, Data Science, Startups and Technology projects to more than 30K readers. You can subscribe to Tech Brew :

For Python Projects —

For complete 60 days of Data Science and ML : Day 1 — Day 60 : Quick Recap of 60 days of Data Science and ML

Follow for more updates. Stay tuned and keep coding!

For other projects, tune to —

Build Machine Learning Pipelines( With Code)

Recurrent Neural Network with Keras

Clustering Geolocation Data in Python using DBSCAN and K-Means

Facial Expression Recognition using Keras

Hyperparameter Tuning with Keras Tuner

Custom Layers in Keras

Software Development
Tech
Programming
Data Science
Machine Learning
Recommended from ReadMedium