Data Structure & Algorithms
  • 🖌️Unlocking the Power of Algorithms with C#
  • Data Structure
    • Data Structure
    • Big O
    • Array
    • Linked Lists
    • Stacks
    • Queues
    • Hash Tables
    • Trees
    • Graphs
    • Heap Sort
    • ParkingLot Algorithm
    • LRU cache
    • Priority Queue
  • Algorithms
    • Algorithm
    • Recursion
    • Sorting
    • Searching
    • Dynamic Programming
  • Problems
    • Array
      • Two Sum
      • Two Sum II - Input Array Is Sorted
      • Contains Duplicate
      • Maximum Subarray
      • House Robber
      • Move Zeroes
      • Rotate Array
      • Plus One
      • Find number of subarrays with even length
      • Find number of subarrays with even sum
      • Find Missing Element
      • Reduce Array Size to The Half
      • Remove Duplicates
      • Merge Sorted Arrays
      • Arrays Intersection
      • 3Sum
      • Trapping Rain Water
      • Maximum sum of a subarray
      • Longest Subarray
      • Subarray Sum Equals K
      • Container With Most Water
      • Missing Number
      • Roman to Integer
      • First Missing Positive
      • Unique Integers That Sum Up To 0
      • Integer to Roman
      • Flatten
    • String
      • Check if two strings are permutation of each other
      • String Compression
      • Palindrome Permutation
      • Determine if a string has all Unique Characters
      • One Away
      • Longest Substring Without Repeating Characters
      • Valid Palindrome
      • Valid Palindrome II
      • Backspace String Compare
      • First Unique Character in a String
      • Is Subsequence
      • URLify a given string
      • String has same characters at same position
      • Number of Ways to Split a String
      • Check whether two Strings are anagram of each other
      • Print last `n` lines of a big file or big string.
      • Multiply Strings
    • Matrix
      • Search a 2D Matrix
      • Search a 2D Matrix II
      • Rotate Matrix
      • Spiral Matrix
      • Set Matrix Zeroes
    • Bit Manipulation
      • Sum of Two Integers
      • Reverse Number
      • Reverse Number II
      • Binary Bits Count
      • Binary Bits Count II
    • Stack
      • Valid Parentheses
      • Balance or not expression
      • Decode String
    • Tree
      • Binary Tree Inorder Traversal
      • Binary Tree Preorder Traversal
      • Binary Tree Postorder Traversal
      • Binary Tree Level Order Traversal
      • Binary Tree Return All Root-To-Leaf Paths
      • Binary Tree Height-Balanced
      • Valid Binary Search Tree
      • Binary Tree Sum of all left leaves.
    • Linked List
      • Linked List Delete Middle Node
      • Merge Sorted Linked List
      • Reverse Linked List
      • Remove Duplicates from Sorted List
      • Remove Duplicates from Unsorted List
      • Linked List Cycle
    • Graph
      • The Number Of Islands
      • Number of Closed Islands
      • Max Area of Island
      • Rotting Oranges
      • Number of Provinces
      • Course Schedule
      • Surrounded Regions
      • Snakes and Ladders
      • Widest Path Without Trees
      • Knight Probability in Chessboard
      • Possible moves of knight
      • Check Knight Tour Configuration
      • Steps by Knight
      • Network Delay Time
    • Greedy
      • Best Time to Buy and Sell Stock
      • Best Time to Buy and Sell Stock II
      • Smallest Subset Array
      • Jump Game
    • Backtracking
      • Towers of Hanoi
      • Subsets
      • Combination Sum
      • Sudoku Solver
      • Word Search
    • Heap
      • Kth Largest Element in an Array
      • Top K Frequent Elements
    • Sorting
      • Order Colors String
    • Recursion
      • Number To Text
      • Divide Number
Powered by GitBook
On this page
  1. Algorithms

Recursion

Recursion

Recursion is a process in which a function calls itself directly or indirectly. It’s a technique used to solve problems by breaking them down into smaller, more manageable sub-problems. A recursive function must have a base case or stopping criteria to avoid infinite recursion.

Backtracking

Backtracking is an algorithmic technique for solving problems recursively by trying to build a solution incrementally, one piece at a time, removing those solutions that fail to satisfy the constraints of the problem at any point in time (by time, here, is referred to the time elapsed till reaching any level of the search tree).

Examples

The Factorial

In mathematics, the factorial of a non-negative integer, denoted by n!, is the product of all positive integers less than or equal to n. For example, the factorial of 3 represents the multiplication of numbers 3, 2, 1, i.e 3! = 3 × 2 × 1 and is equal to 6.

Let's implement it with recursion:

 
    Console.WriteLine(Factorial(3));

public partial class Program 
{

    public static int Factorial(int number)
    {
        if (number < 1)
        {
            return 1;
        }

        return number * Factorial(number - 1);

    }
}

Complexity

  • Time complexity: O(N)

  • Space complexity: O(1)

The Fibonacci series

In the Fibonacci series, each number is the sum of the two preceding ones. For an example: 0,1,1,2,3,5,8,13,21.

Let's implement it with recursion:


for (int i = 0; i < 5; i++)
{
    Console.WriteLine(Fibonacci(i));
}



public partial class Program 
{
    public static int Fibonacci(int number)
    {

        if (number < 2)
        {
            return number;
        }

        return Fibonacci(number - 1) + Fibonacci(number - 2);
    }
}

Complexity

  • Time complexity: O(2^N)

  • Space complexity: O(1)

As we know, O(2^N) time complexity is not good as per performance prospactive. Can we improve it? Yes, we can with the help of dynamic programming (Memoization/Caching). For an example:

for (int i = 0; i < 10; i++)
{
    Console.WriteLine(Fibonacci(i));
}



public partial class Program 
{
    private static Dictionary<int, int> fibonacci = new();
    public static int Fibonacci(int number)
    {
        if (number < 2)
        {
            return number;
        }

        // check result in cache
        if (fibonacci.ContainsKey(number))
        {
            return fibonacci[number];
        }

        var result =  Fibonacci(number - 1) + Fibonacci(number - 2);
        fibonacci[number] = result;
        return result;
    }
}

Complexity

  • Time complexity: O(N). This is because the function only computes each Fibonacci number once due to memoization.

  • Space complexity: O(N). This is because the algorithm uses a dictionary to store the Fibonacci numbers, and the size of this dictionary grows linearly with n, the number of numbers generated.

NOTE: Always cache repetitive steps data.

PreviousAlgorithmNextSorting

Last updated 1 year ago