The Wayback Machine - https://web.archive.org/web/20241003054614/https://www.geeksforgeeks.org/recurrence-relations-a-complete-guide/
Open In App

Recurrence Relations | A Complete Guide

Last Updated : 29 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Have you ever wondered how to calculate the time complexity of algorithms like Fibonacci Series, Merge Sort, etc. where the problem is solved by dividing it into subproblems. This is done by analyzing the Recurrence Relations of these algorithms. In this article, we will learn about the basics of Recurrence Relations and how to analyze them.

What is Recurrence Relation?

A recurrence relation is a mathematical expression that defines a sequence in terms of its previous terms. In the context of algorithmic analysis, it is often used to model the time complexity of recursive algorithms.

General form of a Recurrence Relation: [Tex]a_{n} = f(a_{n-1}, a_{n-2},….,a_{n-k}) [/Tex]
where f is a function that defines the relationship between the current term and the previous terms

Significance of Recurrence Relations in DSA:

Recurrence Relations play a significant role in analyzing and optimizing the complexity of algorithms. Having a strong understanding of Recurrence Relations play a great role in developing the problem-solving skills of an individual. Some of the common uses of Recurrence Relations are:

  • Time Complexity Analysis
  • Generalizing Divide and Conquer Algorithms
  • Analyzing Recursive Algorithms
  • Defining State and Transitions for Dynamic Programming.

Common Examples of Recurrence Relations:

Example

Recurrence Relation

Fibonacci Sequence

F(n) = F(n-1) + F(n-2)

Factorial of a number n

F(n) = n * F(n-1)

Merge Sort

T(n) = 2*T(n/2) + O(n)

Tower of Hanoi

H(n) = 2*H(n-1) + 1

Binary Search

T(n) = T(n/2) + 1

Types of Recurrence Relations:

Various types of Recurrence Relations are:

  1. Linear Recurrence Relations
  2. Divide and Conquer Recurrences
  3. Substitution Recurrences
  4. Homogeneous Recurrences
  5. Non-Homogeneous Recurrences

1. Linear Recurrence Relations:

Following are some of the examples of recurrence relations based on linear recurrence relation.

T(n) = T(n-1) + n for n > 0 and T(0) = 1

These types of recurrence relations can be easily solved using substitution method.
For example,

T(n) = T(n-1) + n
= T(n-2) + (n-1) + n
= T(n-k) + (n-(k-1))….. (n-1) + n

Substituting k = n, we get

T(n) = T(0) + 1 + 2+….. +n = n(n+1)/2 = O(n^2)

2. Divide and conquer recurrence relations:

Following are some of the examples of recurrence relations based on divide and conquer.

T(n) = 2T(n/2) + cn
T(n) = 2T(n/2) + √n

These types of recurrence relations can be easily solved using Master Method.
For recurrence relation: T(n) = 2T(n/2) + cn, the values of a = 2, b = 2 and k =1. Here logb(a) = log2(2) = 1 = k. Therefore, the complexity will be Θ(nlog2(n)).
Similarly for recurrence relation T(n) = 2T(n/2) + √n, the values of a = 2, b = 2 and k =1/2. Here logb(a) = log2(2) = 1 > k. Therefore, the complexity will be Θ(n).

3. Substitution Recurrences:

Sometimes, recurrence relations can’t be directly solved using techniques like substitution, recurrence tree or master method. Therefore, we need to convert the recurrence relation into appropriate form before solving. For example,

T(n) = T(√n) + 1

To solve this type of recurrence, substitute n = 2^m as:

T(2^m) = T(2^m /2) + 1
Let T(2^m) = S(m),
S(m) = S(m/2) + 1

Solving by master method, we get

S(m) = Θ(logm)
As n = 2^m or m = log2(n),
T(n) = T(2^m) = S(m) = Θ(logm) = Θ(loglogn)

4. Homogeneous Recurrence Relations:

A homogeneous recurrence relation is one in which the right-hand side is equal to zero. Mathematically, a homogeneous recurrence relation of order k is represented as:

[Tex]a_{n} = f(a_{n-1}, a_{n-2},…, a_{n-k}) [/Tex]

with the condition that the above equation equates to 0.

Example: [Tex]a_{n} = 2*a_{n-1} – a_{n-2} [/Tex]

5. Non-Homogeneous Recurrence Relations:

A non-homogeneous recurrence relation is one in which the right-hand side is not equal to zero. It can be expressed as:

[Tex]a_{n} = f(a_{n-1}, a_{n-2},…,a_{n-k}) + g(n) [/Tex]

where g(n) is a function that introduces a term not dependent on the previous terms. The presence of g(n) makes the recurrence non-homogeneous.
Example: [Tex]a_{n} = 2*a_{n-1}- a_{n-2} + 3^n [/Tex]

In this case, the term 3^n on the right-hand side makes the recurrence non-homogeneous.

Ways to Solve Recurrence Relations:

Here are the general steps to analyze the complexity of a recurrence relation:

  • Substitute the input size into the recurrence relation to obtain a sequence of terms.
  • Identify a pattern in the sequence of terms, if any, and simplify the recurrence relation to obtain a closed-form expression for the number of operations performed by the algorithm.
  • Determine the order of growth of the closed-form expression by using techniques such as the Master Theorem, or by finding the dominant term and ignoring lower-order terms.
  • Use the order of growth to determine the asymptotic upper bound on the running time of the algorithm, which can be expressed in terms of big O notation.

It’s important to note that the above steps are just a general outline and that the specific details of how to analyze the complexity of a recurrence relation can vary greatly depending on the specific recurrence relation being analyzed.

We have already discussed the analysis of loops. Many algorithms are recursive. When we analyze them, we get a recurrence relation for time complexity. We get running time on an input of size n as a function of n and the running time on inputs of smaller sizes. For example, in Merge Sort, to sort a given array, we divide it into two halves and recursively repeat the process for the two halves. Finally, we merge the results. Time complexity of Merge Sort can be written as T(n) = 2T(n/2) + cn. There are many other algorithms like Binary Search, Tower of Hanoi, etc. 

Overall, solving recurrences plays a crucial role in the analysis, design, and optimization of algorithms, and is an important topic in computer science.
There are mainly three ways of solving recurrences:

  1. Substitution Method
  2. Recurrence Tree Method
  3. Master Method

1. Substitution Method:

We make a guess for the solution and then we use mathematical induction to prove the guess is correct or incorrect. 

For example, consider the recurrence T(n) = 2T(n/2) + n

We guess the solution as T(n) = O(nLogn). Now we use induction to prove our guess.

We need to prove that T(n) <= cnLogn. We can assume that it is true for values smaller than n.

T(n) = 2T(n/2) + n
     <= 2cn/2Log(n/2) + n
       =  cnLogn – cnLog2 + n
       =  cnLogn – cn + n
    <= cnLogn

2. Recurrence Tree Method:

In this method, we draw a recurrence tree and calculate the time taken by every level of the tree. Finally, we sum the work done at all levels. To draw the recurrence tree, we start from the given recurrence and keep drawing till we find a pattern among levels. The pattern is typically arithmetic or geometric series. 

Consider the recurrence relation, T(n) = T(n/4) + T(n/2) + cn2

            cn2
            /      \
  T(n/4)     T(n/2)

If we further break down the expression T(n/4) and T(n/2), we get the following recursion tree.

                    cn2
              /          \      
    c(n2)/16          c(n2)/4
   /         \            /         \
T(n/16)  T(n/8)  T(n/8)    T(n/4) 

Breaking down further gives us following

                        cn2 
                /               \     
       c(n2)/16               c(n2)/4
    /          \               /          \
c(n2)/256  c(n2)/64 c(n2)/64   c(n2)/16
 /    \            /    \       /    \        /    \  

To know the value of T(n), we need to calculate the sum of tree nodes level by level. If we sum the above tree level by level, we get the following series T(n) = c(n^2 + 5(n^2)/16 + 25(n^2)/256) + ….
The above series is a geometrical progression with a ratio of 5/16.

To get an upper bound, we can sum the infinite series. We get the sum as (n2)/(1 – 5/16) which is O(n2)

3. Master Method:

Master Method is a direct way to get the solution. The master method works only for the following type of recurrences or for recurrences that can be transformed into the following type. 
 

T(n) = aT(n/b) + f(n) where a >= 1 and b > 1

There are the following three cases: 

  • If f(n) = O(nc) where c < Logba then T(n) = Θ(nLogba) 
  • If f(n) = Θ(nc) where c = Logba then T(n) = Θ(ncLog n) 
  • If f(n) = Ω(nc) where c > Logba then T(n) = Θ(f(n)) 

How does this work? 

The master method is mainly derived from the recurrence tree method. If we draw the recurrence tree of T(n) = aT(n/b) + f(n), we can see that the work done at the root is f(n), and work done at all leaves is Θ(nc) where c is Logba. And the height of the recurrence tree is Logbn 
 

Master Theorem

In the Recurrence Tree Method, we calculate the total work done. If the work done at leaves is polynomial more, then leaves are the dominant part, and our result becomes the work done at leaves (Case 1). If work done at leaves and root is asymptotically the same, then our result becomes height multiplied by work done at any level (Case 2). If work done at the root is asymptotically more, then our result becomes work done at the root (Case 3). 

Examples of some standard algorithms whose time complexity can be evaluated using the Master Method 

  • Merge Sort: T(n) = 2T(n/2) + Θ(n). It falls in case 2 as c is 1 and Logba] is also 1. So, the solution is Θ(n Logn) 
  • Binary Search: T(n) = T(n/2) + Θ(1). It also falls in case 2 as c is 0 and Logba is also 0. So, the solution is Θ(Logn)


Similar Reads

Different types of recurrence relations and their solutions
In this article, we will see how we can solve different types of recurrence relations using different approaches. Before understanding this article, you should have idea about recurrence relations and different method to solve them (See : Worst, Average and Best Cases, Asymptotic Notations, Analysis of Loops). Type 1: Divide and Conquer Recurrence
3 min read
Substitution Method to solve Recurrence Relations
Recursion is a method to solve a problem where the solution depends on solutions to smaller subproblems of the same problem. Recursive functions (function calling itself) are used to solve problems based on Recursion. The main challenge with recursion is to find the time complexity of the Recursive function. In this article, we will learn about how
6 min read
How to solve time complexity Recurrence Relations using Recursion Tree method?
The Recursion Tree Method is a way of solving recurrence relations. In this method, a recurrence relation is converted into recursive trees. Each node represents the cost incurred at various levels of recursion. To find the total cost, costs of all levels are summed up. Steps to solve recurrence relation using recursion tree method: Draw a recursiv
4 min read
Find nth term of a given recurrence relation
Let an be a sequence of numbers, which is defined by the recurrence relation a1=1 and an+1/an=2n. The task is to find the value of log2(an) for a given n. Examples: Input: 5 Output: 10 Explanation: log2(an) = (n * (n - 1)) / 2 = (5*(5-1))/2 = 10Input: 100 Output: 4950 [Tex]\frac{a_{n+1}}{a_{n}}=2^{n} [/Tex][Tex]\frac{a_{n}}{a_{n-1}}=2^{n-1} [/Tex][
3 min read
Solving Homogeneous Recurrence Equations Using Polynomial Reduction
A recurrence relation is an equation that recursively defines a sequence or multidimensional array of values, once one or more initial terms are given; each further term of the sequence or array is defined as a function of the preceding terms. Below are the steps required to solve a recurrence equation using the polynomial reduction method: Form a
8 min read
Nth term of a recurrence relation generated by two given arrays
Given an integer N and two arrays F[] and C[] of size K that represent the first K terms and coefficient of first K terms of the below recurrence relation respectively. FN = C1*FN - 1 + C2*FN - 2 + C3*FN - 3 +....+ CK*FN - K. The task is to find the Nth term of the recurrence relation. Since the number can be very large take modulo to 109 + 7.Examp
15+ min read
Nth term of given recurrence relation having each term equal to the product of previous K terms
Given two positive integers N and K and an array F[] consisting of K positive integers. The Nth term of the recurrence relation is given by: FN = FN - 1 * FN - 2 * FN - 3 *.......* FN - K The task is to find the Nth term of the given recurrence relation. As the Nth term can be very large, print the Nth term modulo 109 + 7. Examples: Input: N = 5, K
15+ min read
Recurrence Relation in python
Recurrence relation is an equation that recursively defines a sequence, where the next term is a function of the previous terms. Recurrence relations are commonly used to describe the runtime of recursive algorithms in computer science and to define sequences in mathematics. What is a Recurrence Relation?A Recurrence Relation defines a sequence whe
3 min read
How to analyse Complexity of Recurrence Relation
The analysis of the complexity of a recurrence relation involves finding the asymptotic upper bound on the running time of a recursive algorithm. This is usually done by finding a closed-form expression for the number of operations performed by the algorithm as a function of the input size, and then determining the order of growth of the expression
7 min read
Number of Symmetric Relations on a Set
Given a number n, find out the number of Symmetric Relations on a set of first n natural numbers {1, 2, ..n}. Examples: Input : n = 2 Output : 8 Given set is {1, 2}. Below are all symmetric relation. {} {(1, 1)}, {(2, 2)}, {(1, 1), (2, 2)}, {(1, 2), (2, 1)} {(1, 1), (1, 2), (2, 1)}, {(2, 2), (1, 2), (2, 1)}, {(1, 1), (2, 2), (2, 1), (1, 2)} Input :
4 min read
Number of relations that are neither Reflexive nor Irreflexive on a Set
Given a positive integer N, the task is to find the number of relations that are neither reflexive nor irreflexive on a set of first N natural numbers. Since the count of relations can be very large, print it to modulo 109 + 7. A relation R on a set A is called reflexive, if no (a, a) € R holds for every element a € A.For Example: If set A = {a, b}
7 min read
Check if it is possible to assign values such that all the given relations are satisfied
Given an array of strings arr[], where each arr[i] is of the form "i==j" or "i!=j", where i and j are variables representing relationships among them, the task is to check if it is possible to assign values to the variables that satisfy all the relations. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: arr[] = {"i==j"
10 min read
Number of Irreflexive Relations on a Set
Given a positive integer N, the task is to find the number of irreflexive relations that can be formed over the given set of elements. Since the count can be very large, print it to modulo 109 + 7. A relation R on a set A is called reflexive if no (a, a) € R holds for every element a € A.For Example: If set A = {a, b} then R = {(a, b), (b, a)} is i
6 min read
Number of Antisymmetric Relations on a set of N elements
Given a positive integer N, the task is to find the number of Antisymmetric Relations on the given set of N elements. Since the number of relations can be very large, so print it modulo 109+7. A relation R on a set A is called Antisymmetric if and only if (a, b) € R and (b, a) € R, then a = b is called antisymmetric, i.e., the relation R = {(a, b)→
6 min read
Number of Relations that are both Irreflexive and Antisymmetric on a Set
Given a positive integer N, the task is to find the number of relations that are irreflexive antisymmetric relations that can be formed over the given set of elements. Since the count can be very large, print it to modulo 109 + 7. A relation R on a set A is called reflexive if no (a, a) € R holds for every element a € A.For Example: If set A = {a,
6 min read
Check if empty spaces of Array can be filled maintaining given relations of adjacent
Given two arrays, array A[] of size N and array B[] of size N-1, array A has all the positive elements and -1 for the empty values and array B has 3 characters {'>', '=', '<'} which indicates the following: '>' means A[i] > A[i+1]'=' means A[i] = A[i+1]'<' means A[i] < A[i+1] The task is to find if we can fill -1(empty values) of
12 min read
Number of Reflexive Relations on a Set
Given a number n, find out the number of Reflexive Relation on a set of first n natural numbers {1, 2, ..n}. Examples : Input: n = 2Output: 4The given set A = {1, 2}. The following are reflexive relations on A * A :{{1, 1), (2, 2)}{(1, 1), (2, 2), (1, 2)}{(1, 1), (2, 2), (1, 2), (2, 1)}{(1, 1), (2, 2), (2, 1)} Input: n = 3Output: 64 Explanation :Re
3 min read
Number of Asymmetric Relations on a set of N elements
The number of asymmetric relations on a set of ? elements can be calculated using combinatorial principles. An asymmetric relation is a relation that satisfies the condition that if an element ? is related to ?, then ? is not related to ? (formally, ?(?,?) implies not ?(?,?) for all ?≠? in the set). Let's define the set ? as having ? elements. For
7 min read
Number of possible Equivalence Relations on a finite set
An equivalence relation is Reflexive, Symmetric and Transitive. Before counting the number of possible equivalence relations on a set |A|=n, let us see an example of a equivalence relation and identify Equivalence Classes in it. Let A = {1, 2, 3, 4} be a set and R = {(1, 1), (1, 2), (2, 1), (2, 2), (3, 3), (3, 4), (4, 3), (4, 4)} be an equivalence
4 min read
Complete Guide to Install C++17 on Windows
In the Competitive Programming field C++ is one of the most used language, because of it's huge STL(standard template library) functions, and day by day its getting updated. So here is the complete guide to install the latest version of C++(C++ 17) and also setup guide for Sublime Text and CodeBlocks. Install C++17 Compiler(GCC 9.2) To install C++1
3 min read
Maths for Data Structure and Algorithms (DSA) | A Complete Guide
Maths is a fundamental component of learning Data Structure and Algorithms, just like in programming. Maths is primarily used to evaluate the effectiveness of different algorithms. However, there are situations when the answer requires some mathematical understanding or the problem has mathematical characteristics and certain problems demand more t
15+ min read
SDE SHEET - A Complete Guide for SDE Preparation
Here is a curated list of the most popular questions among important topics, such as Programming Languages, Data Structure and Algorithms (DSA), CS Subjects, Aptitude, etc, asked in the Software Development Engineer Interviews. This sheet contains a wide range of coding questions from different Data Structures and Algorithms.It covers all the segme
8 min read
Competitive Programming - A Complete Guide
Competitive Programming is a mental sport that enables you to code a given problem under provided constraints. The purpose of this article is to guide every individual possessing a desire to excel in this sport. This article provides a detailed syllabus for Competitive Programming designed by industry experts to boost the preparation of the readers
8 min read
A Quick Guide on DSA and Competitive Coding in Java
Data Structures and Algorithms (DSA) are the building blocks of efficient and optimized software solutions, especially in the realm of competitive coding. In this quick guide, we'll explore key concepts of DSA using Java, a versatile and widely used programming language. Table of Content Arrays In Java:Strings In Java:Stack in Java:Queue in Java: L
11 min read
Binary Lifting Guide for Competitive Programming
Binary Lifting is a Dynamic Programming approach for trees where we precompute some ancestors of every node. It is used to answer a large number of queries where in each query we need to find an arbitrary ancestor of any node in a tree in logarithmic time. The idea behind Binary Lifting:1. Preprocessing in Binary Lifting:In preprocessing, we initia
15+ min read
Data Structures & Algorithms (DSA) Guide for Google Tech interviews
Google is known for its rigorous and highly competitive technical interviews. These interviews are designed to assess a candidate's problem-solving abilities, technical knowledge, and cultural fit with the company. Preparing for technical interviews at top companies like Google requires a solid understanding of Data Structures and Algorithms (DSA).
9 min read
Substrings: A Comprehensive Guide
Substrings are a fundamental concept in computer science and programming. They play a crucial role in various applications, from text manipulation to data processing. In this blog post, we'll explore what substrings are, their full form, use cases, examples, when to use them, when to avoid them, best practices, common problems, and other relevant i
8 min read
The Ultimate Beginner's Guide For DSA
Every great programmer, like you, works to develop code that is as efficient as possible and produces the best results. So the main goal of every programmer is not to merely write a code that works but to write a well-structured code that works efficiently. This skill can only be developed if one has a solid understanding of Data Structures and Alg
15+ min read
Array Data Structure Guide
An array data structure is a fundamental concept in computer science that stores a collection of elements in a contiguous block of memory. It allows for efficient access to elements using indices and is widely used in programming for organizing and manipulating data. Table of Content What is an Array? Need of Array Data Structures Types of Array Da
5 min read
How to Calculate Standard Deviation in Excel: Quick Guide with Formulas and Examples
Understanding standard deviation in Excel is crucial for anyone looking to measure the spread or variability of a data set. Whether you're a student analyzing exam scores, a business professional evaluating sales data, or a researcher interpreting experimental results, knowing how to calculate standard deviation in Excel can provide valuable insigh
11 min read