# Maximum number of uncrossed lines between two given arrays

Last Updated : 20 Oct, 2023

Given two arrays A[] and B[], the task is to find the maximum number of uncrossed lines between the elements of the two given arrays.

A straight line can be drawn between two array elements A[i] and B[j] only if:

• A[i] = B[j]
• The line does not intersect any other line.

Examples:

Input: A[] = {3, 9, 2}, B[] = {3, 2, 9}
Output:
Explanation:
The lines between A[0] to B[0] and A[1] to B[2] does not intersect each other.

Input: A[] = {1, 2, 3, 4, 5}, B[] = {1, 2, 3, 4, 5}
Output: 5

Naive Approach: The idea is to generate all the subsequences of array A[] and try to find them in array B[] so that the two subsequences can be connected by joining straight lines. The longest such subsequence found to be common in A[] and B[] would have the maximum number of uncrossed lines. So print the length of that subsequence.

Time Complexity: O(M * 2N
Auxiliary Space: O(1)

Efficient Approach: From the above approach, it can be observed that the task is to find the longest subsequence common in both the arrays. Therefore, the above approach can be optimized by finding the Longest Common Subsequence between the two arrays using Dynamic Programming.

Below is the implementation of the above approach:

## C++

 // C++ program for the above approach   #include using namespace std;   // Function to count maximum number // of uncrossed lines between the // two given arrays int uncrossedLines(int* a, int* b,                    int n, int m) {     // Stores the length of lcs     // obtained upto every index     int dp[n + 1][m + 1];       // Iterate over first array     for (int i = 0; i <= n; i++) {           // Iterate over second array         for (int j = 0; j <= m; j++) {               if (i == 0 || j == 0)                   // Update value in dp table                 dp[i][j] = 0;               // If both characters             // are equal             else if (a[i - 1] == b[j - 1])                   // Update the length of lcs                 dp[i][j] = 1 + dp[i - 1][j - 1];               // If both characters             // are not equal             else                   // Update the table                 dp[i][j] = max(dp[i - 1][j],                                dp[i][j - 1]);         }     }       // Return the answer     return dp[n][m]; }   // Driver Code int main() {     // Given array A[] and B[]     int A[] = { 3, 9, 2 };     int B[] = { 3, 2, 9 };       int N = sizeof(A) / sizeof(A[0]);     int M = sizeof(B) / sizeof(B[0]);       // Function Call     cout << uncrossedLines(A, B, N, M);     return 0; }

## Java

 // Java program for the above approach import java.io.*;   class GFG{   // Function to count maximum number // of uncrossed lines between the // two given arrays static int uncrossedLines(int[] a, int[] b,                           int n, int m) {           // Stores the length of lcs     // obtained upto every index     int[][] dp = new int[n + 1][m + 1];       // Iterate over first array     for(int i = 0; i <= n; i++)     {                   // Iterate over second array         for(int j = 0; j <= m; j++)         {             if (i == 0 || j == 0)                               // Update value in dp table                 dp[i][j] = 0;               // If both characters             // are equal             else if (a[i - 1] == b[j - 1])                   // Update the length of lcs                 dp[i][j] = 1 + dp[i - 1][j - 1];               // If both characters             // are not equal             else                   // Update the table                 dp[i][j] = Math.max(dp[i - 1][j],                                     dp[i][j - 1]);         }     }       // Return the answer     return dp[n][m]; }   // Driver Code public static void main (String[] args) {           // Given array A[] and B[]     int A[] = { 3, 9, 2 };     int B[] = { 3, 2, 9 };       int N = A.length;     int M = B.length;       // Function call     System.out.print(uncrossedLines(A, B, N, M)); } }   // This code is contributed by code_hunt

## Python3

 # Python3 program for # the above approach   # Function to count maximum number # of uncrossed lines between the # two given arrays def uncrossedLines(a, b,                    n, m):       # Stores the length of lcs     # obtained upto every index     dp = [[0 for x in range(m + 1)]              for y in range(n + 1)]        # Iterate over first array     for i in range (n + 1):            # Iterate over second array         for j in range (m + 1):                if (i == 0 or j == 0):                    # Update value in dp table                 dp[i][j] = 0                # If both characters             # are equal             elif (a[i - 1] == b[j - 1]):                    # Update the length of lcs                 dp[i][j] = 1 + dp[i - 1][j - 1]                # If both characters             # are not equal             else:                    # Update the table                 dp[i][j] = max(dp[i - 1][j],                                dp[i][j - 1])        # Return the answer     return dp[n][m]    # Driver Code if __name__ == "__main__":         # Given array A[] and B[]     A = [3, 9, 2]     B = [3, 2, 9]        N = len(A)     M = len(B)        # Function Call     print (uncrossedLines(A, B, N, M))   # This code is contributed by Chitranayal

## C#

 // C# program for the above approach using System;   class GFG{   // Function to count maximum number // of uncrossed lines between the // two given arrays static int uncrossedLines(int[] a, int[] b,                           int n, int m) {           // Stores the length of lcs     // obtained upto every index     int[,] dp = new int[n + 1, m + 1];       // Iterate over first array     for(int i = 0; i <= n; i++)     {           // Iterate over second array         for(int j = 0; j <= m; j++)         {             if (i == 0 || j == 0)                   // Update value in dp table                 dp[i, j] = 0;               // If both characters             // are equal             else if (a[i - 1] == b[j - 1])                   // Update the length of lcs                 dp[i, j] = 1 + dp[i - 1, j - 1];               // If both characters             // are not equal             else                   // Update the table                 dp[i, j] = Math.Max(dp[i - 1, j],                                     dp[i, j - 1]);         }     }       // Return the answer     return dp[n, m]; }   // Driver Code public static void Main (String[] args) {           // Given array A[] and B[]     int[] A = { 3, 9, 2 };     int[] B = { 3, 2, 9 };       int N = A.Length;     int M = B.Length;       // Function call     Console.Write(uncrossedLines(A, B, N, M)); } }   // This code is contributed by code_hunt }

## Javascript



Output

2

Time Complexity: O(N*M)
Auxiliary Space: O(N*M)

Efficient approach : Space optimization

In previous approach the dp[i][j] is depend upon the current and previous row of 2D matrix. So to optimize space we use a 1D vectors dp to store previous value  and use prev to store the previous diagonal element and get the current computation.

Implementation Steps:

• Define a vector dp of size m+1 and initialize its first element to 0.
• For each element j in b[], iterate in reverse order from n to 1 and update dp[i] as follows:
a. If a[i – 1] == b[j – 1], set dp[j] to the previous value of dp[i-1]  + 1  (diagonal element).
b. If a[i-1] != b[j-1], set dp[j] to the maximum value between dp[j] and dp[j-1] (value on the left).
• Finally, return dp[m].

Implementation:

## C++

 // C++ code for above approach   #include using namespace std;   // Function to count maximum number // of uncrossed lines between the // two given arrays int uncrossedLines(int* a, int* b, int n, int m) {     // Stores the length of lcs     // obtained upto every index     vector dp(m + 1, 0);       // Iterate over first array     for (int i = 1; i <= n; i++) {           // Initialize prev to 0         int prev = 0;           // Iterate over second array         for (int j = 1; j <= m; j++) {               // Store the current dp[j]             int curr = dp[j];               if (a[i - 1] == b[j - 1])                 dp[j] = prev + 1;               else                 dp[j] = max(dp[j], dp[j - 1]);               // Update prev             prev = curr;         }     }       // Return the answer     return dp[m]; }   // Driver Code int main() {     // Given array A[] and B[]     int A[] = { 3, 9, 2 };     int B[] = { 3, 2, 9 };       int N = sizeof(A) / sizeof(A[0]);     int M = sizeof(B) / sizeof(B[0]);       // Function Call     cout << uncrossedLines(A, B, N, M);     return 0; }   // this code is contributed by bhardwajji

## Java

 // Java code for above approach import java.io.*;   class Main {       // Function to count maximum number   // of uncrossed lines between the   // two given arrays   static int uncrossedLines(int[] a, int[] b, int n, int m)   {             // Stores the length of lcs       // obtained upto every index       int[] dp = new int[m + 1];         // Iterate over first array       for (int i = 1; i <= n; i++) {             // Initialize prev to 0           int prev = 0;             // Iterate over second array           for (int j = 1; j <= m; j++) {                 // Store the current dp[j]               int curr = dp[j];                 if (a[i - 1] == b[j - 1])                   dp[j] = prev + 1;                 else                   dp[j] = Math.max(dp[j], dp[j - 1]);                 // Update prev               prev = curr;           }       }         // Return the answer       return dp[m];   }     // Driver Code   public static void main(String args[]) {       // Given array A[] and B[]       int[] A = { 3, 9, 2 };       int[] B = { 3, 2, 9 };         int N = A.length;       int M = B.length;         // Function Call       System.out.print(uncrossedLines(A, B, N, M));   } }

## Python3

 # Function to count maximum number # of uncrossed lines between the # two given arrays def uncrossedLines(a, b, n, m):     # Stores the length of lcs     # obtained upto every index     dp = [0] * (m + 1)       # Iterate over first array     for i in range(1, n + 1):         # Initialize prev to 0         prev = 0           # Iterate over second array         for j in range(1, m + 1):             # Store the current dp[j]             curr = dp[j]               if a[i - 1] == b[j - 1]:                 dp[j] = prev + 1             else:                 dp[j] = max(dp[j], dp[j - 1])               # Update prev             prev = curr       # Return the answer     return dp[m]     # Driver Code if __name__ == '__main__':     # Given array A[] and B[]     A = [3, 9, 2]     B = [3, 2, 9]       N = len(A)     M = len(B)       # Function Call     print(uncrossedLines(A, B, N, M))

## C#

 // C# code for above approach using System;   class GFG {     // Function to count maximum number   // of uncrossed lines between the   // two given arrays   static int UncrossedLines(int[] a, int[] b, int n,                             int m)   {     // Stores the length of lcs     // obtained upto every index     int[] dp = new int[m + 1];     Array.Fill(dp, 0);       // Iterate over first array     for (int i = 1; i <= n; i++) {         // Initialize prev to 0       int prev = 0;         // Iterate over second array       for (int j = 1; j <= m; j++) {           // Store the current dp[j]         int curr = dp[j];           if (a[i - 1] == b[j - 1])           dp[j] = prev + 1;         else           dp[j] = Math.Max(dp[j], dp[j - 1]);           // Update prev         prev = curr;       }     }       // Return the answer     return dp[m];   }     // Driver Code   public static void Main()   {     // Given array A[] and B[]     int[] A = { 3, 9, 2 };     int[] B = { 3, 2, 9 };       int N = A.Length;     int M = B.Length;       // Function Call     Console.WriteLine(UncrossedLines(A, B, N, M));   } }

## Javascript

 // JavaScript code for above approach   // Function to count maximum number // of uncrossed lines between the // two given arrays function uncrossedLines(a, b, n, m) {   // Stores the length of lcs // obtained upto every index let dp = new Array(m + 1).fill(0);   // Iterate over first array for (let i = 1; i <= n; i++) { // Initialize prev to 0 let prev = 0;   // Iterate over second array for (let j = 1; j <= m; j++) {   // Store the current dp[j]   let curr = dp[j];     if (a[i - 1] == b[j - 1]) dp[j] = prev + 1;   else dp[j] = Math.max(dp[j], dp[j - 1]);     // Update prev   prev = curr; } }   // Return the answer return dp[m]; }   // Driver Code // Given array A[] and B[] let A = [3, 9, 2]; let B = [3, 2, 9];   let N = A.length; let M = B.length;   // Function Call console.log(uncrossedLines(A, B, N, M));

Output

2

Time Complexity: O(N*M)
Auxiliary Space: O(M)

#### Memoization(Top Down) Approach:

0 1 2 3
0 +–+–+–+
|  |  |  |
1 +–+–+–+
|  |? |? |
2 +–+? | + |
|  | + |? |
3 +–+–+? |
|  |  | + |
+–+–+–+

0 1 2 3
0 + 0 0 0
| | | |
1 + 0 1 1
| |?|?|
2 + 0 1+1+
| |+|?|
3 + 0 1 2+
| | |+|
+ + + +

Hint:

First, add one dummy -1 to A and B to represent empty list

Then, we define the notation DP[ y ][ x ].

Let DP[y][x] denote the maximal number of uncrossed lines between A[ 1 … y ] and B[ 1 … x ]

We have optimal substructure as following:

Base case:
Any sequence with empty list yield no uncrossed lines.

If y = 0 or x = 0:
DP[ y ][ x ] = 0

General case:
If A[ y ] == B[ x ]:
DP[ y ][ x ] = DP[ y-1 ][ x-1 ] + 1

Current last number is matched, therefore, add one more uncrossed line

If A[ y ] =/= B[ x ]:
DP[ y ][ x ] = Max( DP[ y ][ x-1 ], DP[ y-1 ][ x ] )

Current last number is not matched,
backtrack to A[ 1…y ]B[ 1…x-1 ], A[ 1…y-1 ]B[ 1…x ]
to find maximal number of uncrossed line

Top-down DP; for each step we can decide to draw the line from the current pointer i (if possible, add this line to the result), or skip this position. Maximize the result of these two choices.

This is a simplified solution when we just scan the other array to find the matching value; we can use some faster lockup method instead. However, the memoisation helps and the simplified solution has the same runtime as the optimized solution with hast set + set.

## C++

 #include using namespace std;   // Function to count maximum number // of uncrossed lines between the // two given arrays     vector>dp; // Stores the length of lcs     // obtained upto every index     int helper(int i,int j,vector&nums1,vector&nums2){       //Check for the base condition         if(i==-1||j==-1)return 0;       //Check if the value already exist in the dp array         if(dp[i][j]!=-1)return dp[i][j];       //check for equality         if(nums1[i]==nums2[j])return dp[i][j]=1+helper(i-1,j-1,nums1,nums2);       //return the max value of the uncrossed lines         return dp[i][j]=max(helper(i-1,j,nums1,nums2),helper(i,j-1,nums1,nums2));     }       int maxUncrossedLines(vector& nums1, vector& nums2) {         int n1=nums1.size();         int n2=nums2.size();           //make the dp array size according to the inputs         dp.resize(n1,vector(n2,-1));           //return the resultant answer         return helper(n1-1,n2-1,nums1,nums2);     }   int main() {     //Declare two vectors     vector A{ 3, 9, 2 };     vector B{ 3, 2, 9 };       // Function Call     cout << maxUncrossedLines(A, B);     return 0; }

## Java

 import java.util.Arrays;   public class GFG {       // Function to count maximum number     // of uncrossed lines between the     // two given arrays     static int[][] dp;       // Stores the length of lcs     // obtained up to every index     static int helper(int i, int j, int[] nums1, int[] nums2) {         // Check for the base condition         if (i == -1 || j == -1)             return 0;         // Check if the value already exists in the dp array         if (dp[i][j] != -1)             return dp[i][j];         // Check for equality         if (nums1[i] == nums2[j])             return dp[i][j] = 1 + helper(i - 1, j - 1, nums1, nums2);         // Return the max value of the uncrossed lines         return dp[i][j] = Math.max(helper(i - 1, j, nums1, nums2),                                    helper(i, j - 1, nums1, nums2));     }       static int maxUncrossedLines(int[] nums1, int[] nums2) {         int n1 = nums1.length;         int n2 = nums2.length;         // Make the dp array size according to the inputs         dp = new int[n1][n2];         for (int[] row : dp) {             Arrays.fill(row, -1);         }         // Return the resultant answer         return helper(n1 - 1, n2 - 1, nums1, nums2);     }       public static void main(String[] args) {         // Declare two arrays         int[] A = {3, 9, 2};         int[] B = {3, 2, 9};           // Function Call         System.out.println(maxUncrossedLines(A, B));     } }

## Python3

 # Function to count maximum number # of uncrossed lines between the # two given arrays def max_uncrossed_lines(nums1, nums2):     # Helper function to calculate the LCS and maximum uncrossed lines     def helper(i, j, nums1, nums2):         # Check for the base condition         if i == -1 or j == -1:             return 0           # Check if the value already exists in the dp array         if dp[i][j] != -1:             return dp[i][j]           # Check for equality         if nums1[i] == nums2[j]:             dp[i][j] = 1 + helper(i - 1, j - 1, nums1, nums2)         else:             # Return the max value of the uncrossed lines             dp[i][j] = max(helper(i - 1, j, nums1, nums2), helper(i, j - 1, nums1, nums2))                   return dp[i][j]       n1 = len(nums1)     n2 = len(nums2)       # Initialize the dp array with -1     dp = [[-1 for _ in range(n2)] for _ in range(n1)]       # Return the result using helper function     return helper(n1 - 1, n2 - 1, nums1, nums2)     # Driver code if __name__ == "__main__":     # Declare two lists     A = [3, 9, 2]     B = [3, 2, 9]       # Function Call     print(max_uncrossed_lines(A, B))

## C#

 using System; using System.Collections.Generic;   class MainClass {     static List> dp;       static int Helper(int i, int j, List nums1, List nums2)     {         // Check for the base condition         if (i == -1 || j == -1) return 0;           // Check if the value already exists in the dp array         if (dp[i][j] != -1) return dp[i][j];           // Check for equality         if (nums1[i] == nums2[j]) return dp[i][j] = 1 + Helper(i - 1, j - 1, nums1, nums2);           // Return the max value of the uncrossed lines         return dp[i][j] = Math.Max(Helper(i - 1, j, nums1, nums2), Helper(i, j - 1, nums1, nums2));     }       static int MaxUncrossedLines(List nums1, List nums2)     {         int n1 = nums1.Count;         int n2 = nums2.Count;           // Make the dp array size according to the inputs         dp = new List>();         for (int i = 0; i < n1; i++)         {             dp.Add(new List());             for (int j = 0; j < n2; j++)             {                 dp[i].Add(-1);             }         }           // Return the resultant answer         return Helper(n1 - 1, n2 - 1, nums1, nums2);     }       public static void Main(string[] args)     {         // Declare two lists         List A = new List { 3, 9, 2 };         List B = new List { 3, 2, 9 };           // Function Call         Console.WriteLine(MaxUncrossedLines(A, B));     } } // This code is contributed by rambabuguphka

## Javascript

 let dp = []; // Stores the length of LCS function GFG(i, j, nums1, nums2) {   // Check for the base condition   if (i === -1 || j === -1) return 0;   // Check if the value already exists in the   // dp array   if (dp[i][j] !== undefined) return dp[i][j];   // Check for equality   if (nums1[i] === nums2[j]) return (dp[i][j] = 1 + GFG(i - 1, j - 1, nums1, nums2));   // Return the max value of the uncrossed lines   return (dp[i][j] = Math.max(GFG(i - 1, j, nums1, nums2), GFG(i, j - 1, nums1, nums2))); } function maxUncrossedLines(nums1, nums2) {   const n1 = nums1.length;   const n2 = nums2.length;   // Make the dp array size according to the inputs   dp = new Array(n1).fill(null).map(() => new Array(n2).fill(undefined));   // Return the resultant answer   return GFG(n1 - 1, n2 - 1, nums1, nums2); } // Main function function main() {   // Declare two arrays   const A = [3, 9, 2];   const B = [3, 2, 9];   // Function Call   console.log(maxUncrossedLines(A, B)); } main();

Output

2

Time complexity: O(M*N),two loops iterations

Auxiliary Space: O(M+N),Exta dp array required to store the desired results