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: 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++
// 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>
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));
}
}
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 <bits/stdc++.h>
using namespace std;
// Function to count maximum number
// of uncrossed lines between the
// two given arrays
vector<vector<int>>dp;
// Stores the length of lcs
// obtained upto every index
int helper(int i,int j,vector<int>&nums1,vector<int>&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<int>& nums1, vector<int>& nums2) {
int n1=nums1.size();
int n2=nums2.size();
//make the dp array size according to the inputs
dp.resize(n1,vector<int>(n2,-1));
//return the resultant answer
return helper(n1-1,n2-1,nums1,nums2);
}
int main() {
//Declare two vectors
vector<int> A{ 3, 9, 2 };
vector<int> 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<List<int>> dp;
static int Helper(int i, int j, List<int> nums1, List<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(List<int> nums1, List<int> nums2)
{
int n1 = nums1.Count;
int n2 = nums2.Count;
// Make the dp array size according to the inputs
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 the resultant answer
return Helper(n1 - 1, n2 - 1, nums1, nums2);
}
public static void Main(string[] args)
{
// Declare two lists
List<int> A = new List<int> { 3, 9, 2 };
List<int> B = new List<int> { 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();
Time complexity: O(M*N),two loops iterations
Auxiliary Space: O(M+N),Exta dp array required to store the desired results
Similar Reads
Maximum number of intersections possible for any of the N given segments Given an array arr[] consisting of N pairs of type {L, R}, each representing a segment on the X-axis, the task is to find the maximum number of intersections a segment has with other segments. Examples: Input: arr[] = {{1, 6}, {5, 5}, {2, 3}}Output: 2Explanation:Below are the count of each segment t
15+ min read
Maximum path sum in the given arrays with at most K jumps Given three arrays A, B, and C each having N elements, the task is to find the maximum sum that can be obtained along any valid path with at most K jumps.A path is valid if it follows the following properties: It starts from the 0th index of an array.It ends at (N-1)th index of an array.For any elem
15+ min read
C++ Program to Maximize count of corresponding same elements in given Arrays by Rotation Given two arrays arr1[] and arr2[] of N integers and array arr1[] has distinct elements. The task is to find the maximum count of corresponding same elements in the given arrays by performing cyclic left or right shift on array arr1[]. Examples:  Input: arr1[] = { 6, 7, 3, 9, 5 }, arr2[] = { 7, 3,
3 min read
Find minimum y coordinates from set of N lines in a plane Given N lines in a plane in the form of a 2D array arr[][] such that each row consists of 2 integers(say m & c) where m is the slope of the line and c is the y-intercept of that line. You are given Q queries each consist of x-coordinates. The task is to find the minimum possible y-coordinate cor
15+ min read
Count number of pairs of lines intersecting at a Point Given N lines are in the form a*x + b*y = c (a>0 or a==0 & b>0). Find the number of pairs of lines intersecting at a point. Examples: Input: N=5 x + y = 2 x + y = 4 x = 1 x - y = 2 y = 3 Output: 9 Input: N=2 x + 2y = 2 x + 2y = 4 Output: 0 Approach: Parallel lines never intersect so a meth
7 min read
Longest unique subarray of an Array with maximum sum in another Array Given two arrays X[] and Y[] of size N, the task is to find the longest subarray in X[] containing only unique values such that a subarray with similar indices in Y[] should have a maximum sum. The value of array elements is in the range [0, 1000]. Examples: Input: N = 5, X[] = {0, 1, 2, 0, 2}, Y[]
10 min read
Path with maximum product in 2-d array Given a 2D matrix of size N*M. The task is to find the maximum product path from (0, 0) to (N-1, M-1). You can only move to right from (i, j) to (i, j+1) and down from (i, j) to (i+1, j).Examples: Input: arr[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} } Output: 2016 The path with maximum product is : 1-
10 min read
Longest subarray such that adjacent elements have at least one common digit | Set 1 Given an array of N integers, write a program that prints the length of the longest subarray such that adjacent elements of the subarray have at least one digit in common. Examples: Input : 12 23 45 43 36 97 Output : 3 Explanation: The subarray is 45 43 36 which has 4 common in 45, 43 and 3 common i
11 min read
Maximum number of elements without overlapping in a Line Given two arrays X and L of same size N. Xi represent the position in an infinite line. Li represents the range up to which ith element can cover on both sides. The task is to select the maximum number of elements such that no two selected elements overlap if they cover the right or the left side se
7 min read
Maximum K-digit number possible from subsequences of two given arrays Given two arrays arr1[] and arr2[] of length M and N consisting of digits [0, 9] representing two numbers and an integer K(K ? M + N), the task is to find the maximum K-digit number possible by selecting subsequences from the given arrays such that the relative order of the digits is the same as in
12 min read