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: 2
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++
#include <bits/stdc++.h>
using namespace std;
int uncrossedLines( int * a, int * b,
int n, int m)
{
int dp[n + 1][m + 1];
for ( int i = 0; i <= n; i++) {
for ( int j = 0; j <= m; j++) {
if (i == 0 || j == 0)
dp[i][j] = 0;
else if (a[i - 1] == b[j - 1])
dp[i][j] = 1 + dp[i - 1][j - 1];
else
dp[i][j] = max(dp[i - 1][j],
dp[i][j - 1]);
}
}
return dp[n][m];
}
int main()
{
int A[] = { 3, 9, 2 };
int B[] = { 3, 2, 9 };
int N = sizeof (A) / sizeof (A[0]);
int M = sizeof (B) / sizeof (B[0]);
cout << uncrossedLines(A, B, N, M);
return 0;
}
|
Java
import java.io.*;
class GFG{
static int uncrossedLines( int [] a, int [] b,
int n, int m)
{
int [][] dp = new int [n + 1 ][m + 1 ];
for ( int i = 0 ; i <= n; i++)
{
for ( int j = 0 ; j <= m; j++)
{
if (i == 0 || j == 0 )
dp[i][j] = 0 ;
else if (a[i - 1 ] == b[j - 1 ])
dp[i][j] = 1 + dp[i - 1 ][j - 1 ];
else
dp[i][j] = Math.max(dp[i - 1 ][j],
dp[i][j - 1 ]);
}
}
return dp[n][m];
}
public static void main (String[] args)
{
int A[] = { 3 , 9 , 2 };
int B[] = { 3 , 2 , 9 };
int N = A.length;
int M = B.length;
System.out.print(uncrossedLines(A, B, N, M));
}
}
|
Python3
def uncrossedLines(a, b,
n, m):
dp = [[ 0 for x in range (m + 1 )]
for y in range (n + 1 )]
for i in range (n + 1 ):
for j in range (m + 1 ):
if (i = = 0 or j = = 0 ):
dp[i][j] = 0
elif (a[i - 1 ] = = b[j - 1 ]):
dp[i][j] = 1 + dp[i - 1 ][j - 1 ]
else :
dp[i][j] = max (dp[i - 1 ][j],
dp[i][j - 1 ])
return dp[n][m]
if __name__ = = "__main__" :
A = [ 3 , 9 , 2 ]
B = [ 3 , 2 , 9 ]
N = len (A)
M = len (B)
print (uncrossedLines(A, B, N, M))
|
C#
using System;
class GFG{
static int uncrossedLines( int [] a, int [] b,
int n, int m)
{
int [,] dp = new int [n + 1, m + 1];
for ( int i = 0; i <= n; i++)
{
for ( int j = 0; j <= m; j++)
{
if (i == 0 || j == 0)
dp[i, j] = 0;
else if (a[i - 1] == b[j - 1])
dp[i, j] = 1 + dp[i - 1, j - 1];
else
dp[i, j] = Math.Max(dp[i - 1, j],
dp[i, j - 1]);
}
}
return dp[n, m];
}
public static void Main (String[] args)
{
int [] A = { 3, 9, 2 };
int [] B = { 3, 2, 9 };
int N = A.Length;
int M = B.Length;
Console.Write(uncrossedLines(A, B, N, M));
}
}
}
|
Javascript
<script>
function uncrossedLines(a, b, n, m)
{
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;
}
}
for (let i = 0; i <= n; i++)
{
for (let j = 0; j <= m; j++)
{
if (i == 0 || j == 0)
dp[i][j] = 0;
else if (a[i - 1] == b[j - 1])
dp[i][j] = 1 + dp[i - 1][j - 1];
else
dp[i][j] = Math.max(dp[i - 1][j],
dp[i][j - 1]);
}
}
return dp[n][m];
}
let A = [ 3, 9, 2 ];
let B = [3, 2, 9];
let N = A.length;
let M = B.length;
document.write(uncrossedLines(A, B, N, M));
</script>
|
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++
#include <bits/stdc++.h>
using namespace std;
int uncrossedLines( int * a, int * b, int n, int m)
{
vector< int > dp(m + 1, 0);
for ( int i = 1; i <= n; i++) {
int prev = 0;
for ( int j = 1; j <= m; 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]);
prev = curr;
}
}
return dp[m];
}
int main()
{
int A[] = { 3, 9, 2 };
int B[] = { 3, 2, 9 };
int N = sizeof (A) / sizeof (A[0]);
int M = sizeof (B) / sizeof (B[0]);
cout << uncrossedLines(A, B, N, M);
return 0;
}
|
Java
import java.io.*;
class Main {
static int uncrossedLines( int [] a, int [] b, int n, int m)
{
int [] dp = new int [m + 1 ];
for ( int i = 1 ; i <= n; i++) {
int prev = 0 ;
for ( int j = 1 ; j <= m; 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 ]);
prev = curr;
}
}
return dp[m];
}
public static void main(String args[]) {
int [] A = { 3 , 9 , 2 };
int [] B = { 3 , 2 , 9 };
int N = A.length;
int M = B.length;
System.out.print(uncrossedLines(A, B, N, M));
}
}
|
Python3
def uncrossedLines(a, b, n, m):
dp = [ 0 ] * (m + 1 )
for i in range ( 1 , n + 1 ):
prev = 0
for j in range ( 1 , m + 1 ):
curr = dp[j]
if a[i - 1 ] = = b[j - 1 ]:
dp[j] = prev + 1
else :
dp[j] = max (dp[j], dp[j - 1 ])
prev = curr
return dp[m]
if __name__ = = '__main__' :
A = [ 3 , 9 , 2 ]
B = [ 3 , 2 , 9 ]
N = len (A)
M = len (B)
print (uncrossedLines(A, B, N, M))
|
C#
using System;
class GFG {
static int UncrossedLines( int [] a, int [] b, int n,
int m)
{
int [] dp = new int [m + 1];
Array.Fill(dp, 0);
for ( int i = 1; i <= n; i++) {
int prev = 0;
for ( int j = 1; j <= m; 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]);
prev = curr;
}
}
return dp[m];
}
public static void Main()
{
int [] A = { 3, 9, 2 };
int [] B = { 3, 2, 9 };
int N = A.Length;
int M = B.Length;
Console.WriteLine(UncrossedLines(A, B, N, M));
}
}
|
Javascript
function uncrossedLines(a, b, n, m)
{
let dp = new Array(m + 1).fill(0);
for (let i = 1; i <= n; i++)
{
let prev = 0;
for (let j = 1; j <= m; 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]);
prev = curr;
}
}
return dp[m];
}
let A = [3, 9, 2];
let B = [3, 2, 9];
let N = A.length;
let M = B.length;
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 <bits/stdc++.h>
using namespace std;
vector<vector< int >>dp;
int helper( int i, int j,vector< int >&nums1,vector< int >&nums2){
if (i==-1||j==-1) return 0;
if (dp[i][j]!=-1) return dp[i][j];
if (nums1[i]==nums2[j]) return dp[i][j]=1+helper(i-1,j-1,nums1,nums2);
return dp[i][j]=max(helper(i-1,j,nums1,nums2),helper(i,j-1,nums1,nums2));
}
int maxUncrossedLines(vector< int >& nums1, vector< int >& nums2) {
int n1=nums1.size();
int n2=nums2.size();
dp.resize(n1,vector< int >(n2,-1));
return helper(n1-1,n2-1,nums1,nums2);
}
int main() {
vector< int > A{ 3, 9, 2 };
vector< int > B{ 3, 2, 9 };
cout << maxUncrossedLines(A, B);
return 0;
}
|
Java
import java.util.Arrays;
public class GFG {
static int [][] dp;
static int helper( int i, int j, int [] nums1, int [] nums2) {
if (i == - 1 || j == - 1 )
return 0 ;
if (dp[i][j] != - 1 )
return dp[i][j];
if (nums1[i] == nums2[j])
return dp[i][j] = 1 + helper(i - 1 , j - 1 , nums1, nums2);
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;
dp = new int [n1][n2];
for ( int [] row : dp) {
Arrays.fill(row, - 1 );
}
return helper(n1 - 1 , n2 - 1 , nums1, nums2);
}
public static void main(String[] args) {
int [] A = { 3 , 9 , 2 };
int [] B = { 3 , 2 , 9 };
System.out.println(maxUncrossedLines(A, B));
}
}
|
Python3
def max_uncrossed_lines(nums1, nums2):
def helper(i, j, nums1, nums2):
if i = = - 1 or j = = - 1 :
return 0
if dp[i][j] ! = - 1 :
return dp[i][j]
if nums1[i] = = nums2[j]:
dp[i][j] = 1 + helper(i - 1 , j - 1 , nums1, nums2)
else :
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)
dp = [[ - 1 for _ in range (n2)] for _ in range (n1)]
return helper(n1 - 1 , n2 - 1 , nums1, nums2)
if __name__ = = "__main__" :
A = [ 3 , 9 , 2 ]
B = [ 3 , 2 , 9 ]
print (max_uncrossed_lines(A, B))
|
C#
using System;
using System.Collections.Generic;
class MainClass
{
static List<List< int >> dp;
static int Helper( int i, int j, List< int > nums1, List< int > nums2)
{
if (i == -1 || j == -1) return 0;
if (dp[i][j] != -1) return dp[i][j];
if (nums1[i] == nums2[j]) return dp[i][j] = 1 + Helper(i - 1, j - 1, nums1, nums2);
return dp[i][j] = Math.Max(Helper(i - 1, j, nums1, nums2), Helper(i, j - 1, nums1, nums2));
}
static int MaxUncrossedLines(List< int > nums1, List< int > nums2)
{
int n1 = nums1.Count;
int n2 = nums2.Count;
dp = new List<List< int >>();
for ( int i = 0; i < n1; i++)
{
dp.Add( new List< int >());
for ( int j = 0; j < n2; j++)
{
dp[i].Add(-1);
}
}
return Helper(n1 - 1, n2 - 1, nums1, nums2);
}
public static void Main( string [] args)
{
List< int > A = new List< int > { 3, 9, 2 };
List< int > B = new List< int > { 3, 2, 9 };
Console.WriteLine(MaxUncrossedLines(A, B));
}
}
|
Javascript
let dp = [];
function GFG(i, j, nums1, nums2) {
if (i === -1 || j === -1) return 0;
if (dp[i][j] !== undefined) return dp[i][j];
if (nums1[i] === nums2[j]) return (dp[i][j] = 1 + GFG(i - 1, j - 1, nums1, nums2));
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;
dp = new Array(n1).fill( null ).map(() => new Array(n2).fill(undefined));
return GFG(n1 - 1, n2 - 1, nums1, nums2);
}
function main() {
const A = [3, 9, 2];
const B = [3, 2, 9];
console.log(maxUncrossedLines(A, B));
}
main();
|
Time complexity: O(M*N),two loops iterations
Auxiliary Space: O(M+N),Exta dp array required to store the desired results
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
20 Oct, 2023
Like Article
Save Article