You are given n pairs of numbers. In every pair, the first number is always smaller than the second number. A pair (c, d) can follow another pair (a, b) if b < c. Chain of pairs can be formed in this fashion. Find the longest chain which can be formed from a given set of pairs.Â
Source: Amazon Interview | Set 2
For example, if the given pairs are {{5, 24}, {39, 60}, {15, 28}, {27, 40}, {50, 90} }, then the longest chain that can be formed is of length 3, and the chain is {{5, 24}, {27, 40}, {50, 90}}
Method 1: This problem is a variation of standard Longest Increasing Subsequence problem. Following is a simple two step process.Â
1) Sort given pairs in increasing order of first (or smaller) element. Why do we need sorting? Consider the example {{6, 8}, {3, 4}} to understand the need of sorting. If we proceed to second step without sorting, we get output as 1. But the correct output is 2.Â
2) Now run a modified LIS process where we compare the second element of already finalized LIS with the first element of new LIS being constructed.Â
The following code is a slight modification of method 2 of this post.
C++
// CPP program for above approach#include <bits/stdc++.h>using namespace std;Â
// Structure for a Pair class Pair {Â Â Â Â public:Â Â Â Â int a; Â Â Â Â int b; }; Â
// This function assumes that arr[] // is sorted in increasing order // according the first // (or smaller) values in Pairs. int maxChainLength( Pair arr[], int n) {     int i, j, max = 0;     int *mcl = new int[sizeof( int ) * n ];          /* Initialize MCL (max chain length)    values for all indexes */    for ( i = 0; i < n; i++ )         mcl[i] = 1;          /* Compute optimized chain     length values in bottom up manner */    for ( i = 1; i < n; i++ )         for ( j = 0; j < i; j++ )             if ( arr[i].a > arr[j].b &&                     mcl[i] < mcl[j] + 1)                 mcl[i] = mcl[j] + 1;          // mcl[i] now stores the maximum     // chain length ending with Pair i          /* Pick maximum of all MCL values */    for ( i = 0; i < n; i++ )         if ( max < mcl[i] )             max = mcl[i];          /* Free memory to avoid memory leak */         return max; }      Â
/* Driver code */int main() { Â Â Â Â Pair arr[] = { {5, 24}, {15, 25}, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â {27, 40}, {50, 60} }; Â Â Â Â int n = sizeof(arr)/sizeof(arr[0]); Â Â Â Â cout << "Length of maximum size chain is "Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â << maxChainLength( arr, n ); Â Â Â Â return 0; } Â
// This code is contributed by rathbhupendra |
C
#include<stdio.h>#include<stdlib.h>Â
// Structure for a pairstruct pair{Â Â int a;Â Â int b;};Â
// This function assumes that // arr[] is sorted in increasing order// according the first // (or smaller) values in pairs.int maxChainLength( struct pair arr[], int n){Â Â Â int i, j, max = 0;Â Â Â int *mcl = (int*) malloc ( sizeof( int ) * n );Â
   /* Initialize MCL (max chain      length) values for all indexes */   for ( i = 0; i < n; i++ )      mcl[i] = 1;Â
   /* Compute optimized chain length    values in bottom up manner */   for ( i = 1; i < n; i++ )      for ( j = 0; j < i; j++ )         if ( arr[i].a > arr[j].b &&                 mcl[i] < mcl[j] + 1)            mcl[i] = mcl[j] + 1;Â
   // mcl[i] now stores the maximum    // chain length ending with pair i      /* Pick maximum of all MCL values */   for ( i = 0; i < n; i++ )      if ( max < mcl[i] )         max = mcl[i];Â
   /* Free memory to avoid memory leak */   free( mcl );Â
   return max;}Â
Â
/* Driver program to test above function */int main(){    struct pair arr[] = { {5, 24}, {15, 25},                          {27, 40}, {50, 60} };    int n = sizeof(arr)/sizeof(arr[0]);    printf("Length of maximum size chain is %d\n",           maxChainLength( arr, n ));    return 0;} |
Java
// Java program for above approachimport java.io.*;Â
class Pair {Â Â Â Â int a;Â Â Â Â int b;Â
    public Pair(int a, int b)    {        this.a = a;        this.b = b;    }Â
    // This function assumes that    // arr[] is sorted in increasing order    // according the first (or smaller)    // values in pairs.    static int maxChainLength(Pair arr[], int n)    {        int i, j, max = 0;        int mcl[] = new int[n];Â
        /* Initialize MCL (max chain length)         values for all indexes */        for (i = 0; i < n; i++)            mcl[i] = 1;Â
        /* Compute optimized chain length         values in bottom up manner */        for (i = 1; i < n; i++)            for (j = 0; j < i; j++)                if (arr[i].a > arr[j].b                    && mcl[i] < mcl[j] + 1)                    mcl[i] = mcl[j] + 1;Â
        // mcl[i] now stores the maximum        // chain length ending with pair iÂ
        /* Pick maximum of all MCL values */        for (i = 0; i < n; i++)            if (max < mcl[i])                max = mcl[i];Â
        return max;    }Â
    /* Driver program to test above function */    public static void main(String[] args)    {        Pair arr[] = new Pair[] { new Pair(5, 24),                                  new Pair(15, 25),                                  new Pair(27, 40),                                  new Pair(50, 60) };        System.out.println(            "Length of maximum size chain is "            + maxChainLength(arr, arr.length));    }} |
Python3
# Python program for above approachclass Pair(object):    def __init__(self, a, b):        self.a = a        self.b = bÂ
# This function assumes # that arr[] is sorted in increasing# order according the # first (or smaller) values in pairs.def maxChainLength(arr, n):Â Â Â Â Â Â Â Â Â max = 0Â
    # Initialize MCL(max chain     # length) values for all indices    mcl = [1 for i in range(n)]Â
    # Compute optimized chain     # length values in bottom up manner    for i in range(1, n):        for j in range(0, i):            if (arr[i].a > arr[j].b and                  mcl[i] < mcl[j] + 1):                mcl[i] = mcl[j] + 1Â
    # mcl[i] now stores the maximum    # chain length ending with pair iÂ
    # Pick maximum of all MCL values    for i in range(n):        if (max < mcl[i]):            max = mcl[i]Â
    return maxÂ
# Driver program to test above functionarr = [Pair(5, 24), Pair(15, 25), Â Â Â Â Â Â Â Pair(27, 40), Pair(50, 60)]Â
print('Length of maximum size chain is',      maxChainLength(arr, len(arr)))Â
# This code is contributed by Soumen Ghosh |
C#
// Dynamic C# program to find // Maximum Length Chain of Pairsusing System;Â
class Pair {    int a;    int b;         public Pair(int a, int b)     {        this.a = a;        this.b = b;    }         // This function assumes that arr[]     // is sorted in increasing order    // according the first (or smaller)     // values in pairs.    static int maxChainLength(Pair []arr, int n)    {        int i, j, max = 0;        int []mcl = new int[n];                 // Initialize MCL (max chain length)        // values for all indexes         for(i = 0; i < n; i++ )            mcl[i] = 1;                 // Compute optimized chain length         // values in bottom up manner         for(i = 1; i < n; i++)            for (j = 0; j < i; j++)                if(arr[i].a > arr[j].b &&                   mcl[i] < mcl[j] + 1)                              // mcl[i] now stores the maximum           // chain length ending with pair i          mcl[i] = mcl[j] + 1;Â
        // Pick maximum of all MCL values        for ( i = 0; i < n; i++ )            if (max < mcl[i] )                max = mcl[i];                 return max;    }Â
    // Driver Code    public static void Main()     {        Pair []arr = new Pair[]         {new Pair(5,24), new Pair(15, 25),        new Pair (27, 40), new Pair(50, 60)};        Console.Write("Length of maximum size                                 chain is " +                  maxChainLength(arr, arr.Length));    }}Â
// This code is contributed by nitin mittal. |
Javascript
<script>Â
// Javascript program for above approachÂ
class Pair{Â Â Â Â constructor(a,b)Â Â Â Â {Â Â Â Â Â Â Â Â this.a=a;Â Â Â Â Â Â Â Â this.b=b;Â Â Â Â }}Â
// This function assumes that    // arr[] is sorted in increasing order    // according the first (or smaller)    // values in pairs.function maxChainLength(arr,n){    let i, j, max = 0;       let mcl = new Array(n);              /* Initialize MCL (max chain length)        values for all indexes */       for ( i = 0; i < n; i++ )          mcl[i] = 1;              /* Compute optimized chain length        values in bottom up manner */       for ( i = 1; i < n; i++ )          for ( j = 0; j < i; j++ )             if ( arr[i].a > arr[j].b &&                    mcl[i] < mcl[j] + 1)                mcl[i] = mcl[j] + 1;              // mcl[i] now stores the maximum       // chain length ending with pair i              /* Pick maximum of all MCL values */       for ( i = 0; i < n; i++ )          if ( max < mcl[i] )             max = mcl[i];              return max;}Â
/* Driver program to test above function */let arr=[ new Pair(5,24),          new Pair(15, 25),                              new Pair (27, 40),          new Pair(50, 60)];           document.write("Length of maximum size chain is " +                 maxChainLength(arr, arr.length));Â
// This code is contributed by avanitrachhadiya2155</script> |
Length of maximum size chain is 3
Time Complexity: O(n^2) where n is the number of pairs.Â
Auxiliary Space: O(n) because of the extra array used to store maximum chain length.
The given problem is also a variation of Activity Selection problem and can be solved in (nLogn) time. To solve it as a activity selection problem, consider the first element of a pair as start time in activity selection problem, and the second element of pair as end time.Â
Method 2:Â
- Sort given pairs in increasing order of second values.
- Take ans = 0 initially and prev = INT_MIN.
- Now iterate on the given array and if  arr[i].first>prev , then increase answer and set  prev=arr[i].second.
- Finally return answer.
C++
#include <bits/stdc++.h>using namespace std;Â
struct val {Â Â Â Â int first;Â Â Â Â int second;};Â
//function that helps to sort the structure p in increasing order of second valuesbool static comp(val fst, val sec){Â Â Â Â Â Â Â Â return fst.second<sec.second;Â Â Â Â }Â
//function to calculate the max length chain int maxChainLen(struct val p[],int n){        //Your code here        sort(p,p+n,comp);        int prev=-1e9;        int ans=0;        for(int i=0;i<n;i++){            if(p[i].first>prev){                ans++;                prev=p[i].second;            }        }        return ans;    }Â
int main() {Â
Â
    int n = 5;    val p[n];    p[0].first = 5;    p[0].second = 24;       p[1].first = 39;    p[1].second = 60;       p[2].first = 15;    p[2].second = 28;       p[3].first = 27;    p[3].second = 40;       p[4].first = 50;    p[4].second = 90;           // Function Call    cout << maxChainLen(p, n) << endl;    return 0;} |
Java
// Java Implementation for above approachimport java.util.*;import java.io.*;Â
class GFG {Â
  // function to calculate the max length chain  public static int maxChainLen(int p[][], int n) {Â
    Arrays.sort(p, new C());Â
    int prev = -1000000000;    int ans = 0;    for (int i = 0; i < n; i++) {      if (p[i][0] > prev) {        ans++;        prev = p[i][1];      }    }    return ans;  }Â
  // function that helps to sort the structure p in increasing order of second values  public static class C implements Comparator<int[]> {    public int compare(int[] a1, int[] a2) {      return Integer.compare(a1[1], a2[1]);    }  }Â
  // Driver Code  public static void main (String[] args) {    int n = 5;    int[][] p = {{5, 24}, {39, 60}, {15, 28}, {27, 40}, {50, 90}};    // Function Call    System.out.println(maxChainLen(p, n));  }}Â
// This code is contributed by ajaymakvana |
Python3
# Python3 implementation of the approachfrom typing import List, TupleÂ
def max_chain_len(p: List[Tuple[int, int]]) -> int:       # Your code here    p.sort(key=lambda x: x[1])    prev = -1e9    ans = 0    for x in p:        if x[0] > prev:            ans += 1            prev = x[1]    return ansÂ
n = 5p = [    (5, 24),    (39, 60),    (15, 28),    (27, 40),    (50, 90)]Â
# Function Callprint(max_chain_len(p))Â
# This code is contributed by phasing17 |
C#
// C# program to implement the approachusing System;using System.Collections;using System.Collections.Generic;using System.Linq;Â
class GFG{Â Â Â // function to calculate the max length chainpublic static int MaxChainLen(int[][] p, int n){Array.Sort(p, new C());Â Â Â Â int prev = -1000000000;Â Â Â Â int ans = 0;Â Â Â Â for (int i = 0; i < n; i++)Â Â Â Â {Â Â Â Â Â Â Â Â if (p[i][0] > prev)Â Â Â Â Â Â Â Â {Â Â Â Â Â Â Â Â Â Â Â Â ans++;Â Â Â Â Â Â Â Â Â Â Â Â prev = p[i][1];Â Â Â Â Â Â Â Â }Â Â Â Â }Â Â Â Â return ans;}Â
// function that helps to sort the structure p in increasing order of second valuespublic class C : IComparer<int[]>{Â Â Â Â public int Compare(int[] a1, int[] a2)Â Â Â Â {Â Â Â Â Â Â Â Â return Comparer<int>.Default.Compare(a1[1], a2[1]);Â Â Â Â }}Â
// Driver Codestatic void Main(string[] args){    int n = 5;    int[][] p = {        new int[] { 5, 24 },        new int[] { 39, 60 },        new int[] { 15, 28 },        new int[] { 27, 40 },        new int[] { 50, 90 }    };    // Function Call    Console.WriteLine(MaxChainLen(p, n));}Â
}Â
// This code is contributed by phasing17 |
Javascript
// JS code to implement the approachÂ
// JavaScript implementation of the approachfunction maxChainLen(p) {  // Your code here  p.sort((a, b) => a[1] - b[1]);  let prev = -1e9;  let ans = 0;  for (const x of p) {    if (x[0] > prev) {      ans += 1;      prev = x[1];    }  }  return ans;}Â
const n = 5;const p = [ [5, 24],  [39, 60],  [15, 28],  [27, 40],  [50, 90]];Â
// Function Callconsole.log(maxChainLen(p));Â
// This code is contributed by phasing17 |
3
Time Complexity: O(n*log2n).
Auxiliary Space: O(1) as no extra space has been used.
Another approach( Top-down Dynamic programming): Now we will explore the way of solving this problem using the top-down approach of dynamic programming (recursion + memoization).Â
Since we are going to solve the above problem using top down method our first step is to figure out the recurrence relation. The best and the easiest way to get the recurrence relation is to think about the choices that we have at each state or position.Â
If we look at the above problem carefully, we find two choices to be present at each position/index. The two choices are:Â
Choice 1: To select the element at the particular position and explore the rest, (or)Â
Choice 2: To leave the element at that position and explore the rest.Â
Please note here that we can select the element at a particular position only if first element at that position is greater than the second element that we have previously chosen (this is a constraint given in the question). Hence, in the recursion we maintain a variable which would tell us the previous element that we picked.Â
Also, we have to maximize our answer. Hence, we have to find out the maximum resulting option by exploring the above two choices at each position.Â
The resulting recurrence relation would be:Â
  T(n) = max( maxlenchain(p,n,p[pos].second,0)+1,maxlenchain(p,n,prev_choosen_ele,pos+1) )Â
Please note the function signature is as follows:Â
int cal(struct val p[],int n,int prev_choosen_ele,int pos);
Nevertheless, we should not forget our base condition in recursion. If not, our code would enjoy a vacation by just executing forever and not stopping at all.Â
So, our base condition for this problem is quite simple. If we reach the end of our exploration, we just return 0, as no more chains would be possible.
  if(pos >= n) return 0;
To avoid the repetitive task, we do the dynamic programming magic (It is a magic to reduce your time complexity). We store the position and previous element in a map. If we ever happened to come to the same position with the same previous element we do not recompute again. We just return the answer from the map.
Below is the implementation of the above approach:
C++14
// CPP program for above approach#include <bits/stdc++.h>using namespace std;Â
// Structure valstruct val {Â Â Â Â int first;Â Â Â Â int second;};Â
map<pair<int, int>, int> m;Â
// Memoisation functionint findMaxChainLen(struct val p[], int n,                         int prev, int pos){         // Check if pair { pos, prev } exists    // in m    if (m.find({ pos, prev }) != m.end())     {        return m[{ pos, prev }];    }Â
    // Check if pos is >=n     if (pos >= n)        return 0;Â
    // Check if p[pos].first is     // less than prev    if (p[pos].first <= prev)     {        return findMaxChainLen(p, n, prev,                                  pos + 1);    }Â
    else    {        int ans = max(findMaxChainLen(p, n,                              p[pos].second, 0) + 1,                      findMaxChainLen(p, n,                                    prev, pos + 1));        m[{ pos, prev }] = ans;        return ans;    }}Â
// Function to calculate maximum// chain lengthint maxChainLen(struct val p[], int n){    m.clear();       // Call memoisation function    int ans = findMaxChainLen(p, n, 0, 0);    return ans;}Â
// Driver Codeint main(){Â
    int n = 5;    val p[n];    p[0].first = 5;    p[0].second = 24;Â
    p[1].first = 39;    p[1].second = 60;Â
    p[2].first = 15;    p[2].second = 28;Â
    p[3].first = 27;    p[3].second = 40;Â
    p[4].first = 50;    p[4].second = 90;         // Function Call    cout << maxChainLen(p, n) << endl;    return 0;} |
Java
// Java program for above approachimport java.util.*;Â
class GFG{Â
// Structure valstatic class val {Â Â Â Â int first;Â Â Â Â int second;};Â
static class pair{     int first, second;          public pair(int first, int second)     {         this.first = first;         this.second = second;     }         @Override    public int hashCode()    {        final int prime = 31;        int result = 1;        result = prime * result + first;        result = prime * result + second;        return result;    }         @Override    public boolean equals(Object obj)    {        if (this == obj)            return true;        if (obj == null)            return false;        if (getClass() != obj.getClass())            return false;                     pair other = (pair) obj;        if (first != other.first)            return false;        if (second != other.second)            return false;                     return true;    }        } Â
static Map<pair, Integer> m = new HashMap<>();Â
// Memoisation functionstatic int findMaxChainLen(val p[], int n,                            int prev, int pos){         // Check if pair { pos, prev } exists    // in m    if (m.containsKey(new pair(pos, prev)))     {        return m.get(new pair(pos, prev));    }Â
    // Check if pos is >=n     if (pos >= n)        return 0;Â
    // Check if p[pos].first is     // less than prev    if (p[pos].first <= prev)     {        return findMaxChainLen(p, n, prev,                                pos + 1);    }Â
    else    {        int ans = Math.max(findMaxChainLen(                               p, n, p[pos].second, 0) + 1,                           findMaxChainLen(                               p, n, prev, pos + 1));                                        m.put(new pair(pos, prev), ans);        return ans;    }}Â
// Function to calculate maximum// chain lengthstatic int maxChainLen(val p[], int n){    m.clear();       // Call memoisation function    int ans = findMaxChainLen(p, n, 0, 0);    return ans;}Â
// Driver Codepublic static void main(String[] args){Â Â Â Â int n = 5;Â Â Â Â val []p = new val[n];Â Â Â Â for(int i = 0; i < n; i++)Â Â Â Â Â Â Â Â p[i] = new val();Â Â Â Â Â Â Â Â Â Â Â Â Â p[0].first = 5;Â Â Â Â p[0].second = 24;Â
    p[1].first = 39;    p[1].second = 60;Â
    p[2].first = 15;    p[2].second = 28;Â
    p[3].first = 27;    p[3].second = 40;Â
    p[4].first = 50;    p[4].second = 90;         // Function Call    System.out.print(maxChainLen(p, n) + "\n");}}Â
// This code is contributed by 29AjayKumar |
Python3
# Python program for above approachÂ
# Structure valclass val:    def __init__(self,first,second):        self.first = first        self.second = second     # Memoisation functiondef findMaxChainLen(p, n, prev, pos):         global m         # Check if pair { pos, prev } exists    # in m    if (val(pos, prev) in m):        return m[val(pos, prev)]Â
    # Check if pos is >=n    if (pos >= n):        return 0Â
    # Check if p[pos].first is    # less than prev    if (p[pos].first <= prev):        return findMaxChainLen(p, n, prev, pos + 1)Â
    else:        ans = max(findMaxChainLen(p, n,                            p[pos].second, 0) + 1,                    findMaxChainLen(p, n,                                prev, pos + 1))        m[val(pos, prev)] = ans        return ansÂ
# Function to calculate maximum# chain lengthdef maxChainLen(p,n):Â
    global m    m.clear()Â
    # Call memoisation function    ans = findMaxChainLen(p, n, 0, 0)    return ansÂ
# Driver Coden = 5p = [0]*np[0] = val(5,24)Â
p[1] = val(39,60)Â
p[2] = val(15,28)Â
p[3] = val(27,40)Â
p[4] = val(50,90)Â
m = {}Â
# Function Callprint(maxChainLen(p, n))Â
# This code is contributed by shinjanpatra |
C#
// C# program for above approachÂ
using System;using System.Collections.Generic;Â
class GFG{Â
  // Structure val  class val   {    public int first;    public int second;  };Â
  class pair  {     public int first, second; Â
    public pair(int first, int second)     {       this.first = first;       this.second = second;     }Â
    public override int GetHashCode()    {      int prime = 31;      int result = 1;      result = prime * result + first;      result = prime * result + second;      return result;    }Â
    public bool Equals(pair other)    {      return other != null && (other.first == first) && (other.second == second);    }   Â
  } Â
  static Dictionary<pair, int> m = new Dictionary<pair, int>();Â
  // Memoisation function  static int findMaxChainLen(val[] p, int n,                              int prev, int pos)  {Â
    // Check if pair { pos, prev } exists    // in m    if (m.ContainsKey(new pair(pos, prev)))     {      return m[new pair(pos, prev)];    }Â
    // Check if pos is >=n     if (pos >= n)      return 0;Â
    // Check if p[pos].first is     // less than prev    if (p[pos].first <= prev)     {      return findMaxChainLen(p, n, prev,                              pos + 1);    }Â
    else    {      int ans = Math.Max(findMaxChainLen(        p, n, p[pos].second, 0) + 1,                         findMaxChainLen(                           p, n, prev, pos + 1));Â
      m[new pair(pos, prev)] = ans;      return ans;    }  }Â
  // Function to calculate maximum  // chain length  static int maxChainLen(val[] p, int n)  {    m.Clear();Â
    // Call memoisation function    int ans = findMaxChainLen(p, n, 0, 0);    return ans;  }Â
  // Driver Code  public static void Main(string[] args)  {    int n = 5;    val []p = new val[n];    for(int i = 0; i < n; i++)      p[i] = new val();Â
    p[0].first = 5;    p[0].second = 24;Â
    p[1].first = 39;    p[1].second = 60;Â
    p[2].first = 15;    p[2].second = 28;Â
    p[3].first = 27;    p[3].second = 40;Â
    p[4].first = 50;    p[4].second = 90;Â
    // Function Call    Console.WriteLine(maxChainLen(p, n) + "\n");  }}Â
// This code is contributed by phasing17 |
Javascript
<script>Â
// JavaScript program for above approachÂ
Â
// Structure valclass val{Â Â Â Â constructor(first,second){Â Â Â Â Â Â Â Â this.first = first;Â Â Â Â Â Â Â Â this.second = second;Â Â Â Â }};Â
let m = new Map();Â
// Memoisation functionfunction findMaxChainLen(p,n,prev,pos){         // Check if pair { pos, prev } exists    // in m    if (m.has(new val(pos, prev)))        return m.get(new val(pos, prev));Â
    // Check if pos is >=n    if (pos >= n)        return 0;Â
    // Check if p[pos].first is    // less than prev    if (p[pos].first <= prev)    {        return findMaxChainLen(p, n, prev,                                pos + 1);    }Â
    else    {        let ans = Math.max(findMaxChainLen(p, n,                            p[pos].second, 0) + 1,                    findMaxChainLen(p, n,                                prev, pos + 1));        m.set(new val(pos, prev),ans);        return ans;    }}Â
// Function to calculate maximum// chain lengthfunction maxChainLen(p,n){Â Â Â Â m.clear();Â
    // Call memoisation function    let ans = findMaxChainLen(p, n, 0, 0);    return ans;}Â
// Driver Codelet n = 5;let p = new Array(n);p[0] = new val(5,24);Â
p[1] = new val(39,60);Â
p[2] = new val(15,28);Â
p[3] = new val(27,40);Â
p[4] = new val(50,90);Â
// Function Calldocument.write(maxChainLen(p, n),"</br>");Â
// code is contributed by shinjanpatraÂ
</script> |
3
Time Complexity: O(n2).
Auxiliary Space: O(n2), due to the use of a map to store previously calculated values.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
