Skip to content
Related Articles
Open in App
Not now

Related Articles

Maximum number of uncrossed lines between two given arrays

Improve Article
Save Article
Like Article
  • Difficulty Level : Hard
  • Last Updated : 29 Mar, 2023
Improve Article
Save Article
Like Article

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 <bits/stdc++.h>
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




<script>
 
// Javascript program for the 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(n + 1);
    for(let i = 0; i< (n + 1); i++)
    {
        dp[i] = new Array(m + 1);
        for(let j = 0; j < (m + 1); j++)
        {
            dp[i][j] = 0;
        }
    }
   
    // Iterate over first array
    for(let i = 0; i <= n; i++)
    {
         
        // Iterate over second array
        for(let 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
 
// 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
document.write(uncrossedLines(A, B, N, M));
 
// This code is contributed by avanitrachhadiya2155
 
</script>


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 <bits/stdc++.h>
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<int> 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));
  }
}


Output

2

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


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!