Check if two sorted arrays can be merged to form a sorted array with no adjacent pair from the same array
Given two sorted arrays A[] and B[] of size N, the task is to check if it is possible to merge two given sorted arrays into a new sorted array such that no two consecutive elements are from the same array.
Examples:
Input: A[] = {3, 5, 8}, B[] = {2, 4, 6}
Output: Yes
Explanation: Merged array = {B[0], A[0], B[1], A[1], B[2], A[2]}
Since the resultant array is sorted array, the required output is Yes.
Input: A[] = {12, 4, 2, 5, 3}, B[] = {32, 13, 43, 10, 8}
Output: No
Approach: Follow the steps below to solve the problem:
- Initialize a variable, say flag = true to check if it is possible to form a new sorted array by merging the given two sorted arrays such that no two consecutive elements are from the same array.
- Initialize a variable, say prev to check if the previous element of the merge array are from the array A[] or the array B[]. If prev == 1 then the previous element are from the array A[] and if prev == 0 then the previous element are from the array B[].
- Traverse both the array using variables, i and j and check the following conditions:
- If A[i] < B[j] and prev != 0 then increment the value of i and update the value of prev to 0.
- If B[j] < A[i[ and prev != 1 then increment the value of j and update the value of prev to 1.
- If A[i] == B[j] and prev != 1 then increment the value of j and update the value of prev to 1.
- If A[i] == B[j] and prev != 0 then increment the value of i and update the value of prev to 0.
- If none of the above condition satisfy then update flag = false.
- Finally, print the value of flag.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool checkIfPossibleMerge( int A[], int B[], int N)
{
int i = 0;
int j = 0;
int prev = -1;
int flag = 1;
while (i < N && j < N) {
if (A[i] < B[j] && prev != 0) {
prev = 0;
i++;
}
else if (B[j] < A[i] && prev != 1) {
prev = 1;
j++;
}
else if (A[i] == B[j]) {
if (prev != 1) {
prev = 1;
j++;
}
else {
prev = 0;
i++;
}
}
else {
flag = 0;
break ;
}
}
return flag;
}
int main()
{
int A[3] = { 3, 5, 8 };
int B[3] = { 2, 4, 6 };
int N = sizeof (A) / sizeof (A[0]);
if (checkIfPossibleMerge(A, B, N)) {
cout << "Yes" ;
}
else {
cout << "No" ;
}
return 0;
}
|
Java
import java.io.*;
class GFG{
static boolean checkIfPossibleMerge( int [] A, int [] B,
int N)
{
int i = 0 ;
int j = 0 ;
int prev = - 1 ;
boolean flag = true ;
while (i < N && j < N)
{
if (A[i] < B[j] && prev != 0 )
{
prev = 0 ;
i++;
}
else if (B[j] < A[i] && prev != 1 )
{
prev = 1 ;
j++;
}
else if (A[i] == B[j])
{
if (prev != 1 )
{
prev = 1 ;
j++;
}
else
{
prev = 0 ;
i++;
}
}
else
{
flag = false ;
break ;
}
}
return flag;
}
public static void main(String[] args)
{
int [] A = { 3 , 5 , 8 };
int [] B = { 2 , 4 , 6 };
int N = A.length;
if (checkIfPossibleMerge(A, B, N))
{
System.out.println( "Yes" );
}
else
{
System.out.println( "No" );
}
}
}
|
Python3
def checkIfPossibleMerge(A, B, N):
i = 0
j = 0
prev = - 1
flag = 1
while (i < N and j < N):
if (A[i] < B[j] and prev ! = 0 ):
prev = 0
i + = 1
elif (B[j] < A[i] and prev ! = 1 ):
prev = 1
j + = 1
elif (A[i] = = B[j]):
if (prev ! = 1 ):
prev = 1
j + = 1
else :
prev = 0
i + = 1
else :
flag = 0
break
return flag
if __name__ = = '__main__' :
A = [ 3 , 5 , 8 ]
B = [ 2 , 4 , 6 ]
N = len (A)
if (checkIfPossibleMerge(A, B, N)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG{
static bool checkIfPossibleMerge( int [] A, int [] B,
int N)
{
int i = 0;
int j = 0;
int prev = -1;
bool flag = true ;
while (i < N && j < N)
{
if (A[i] < B[j] && prev != 0)
{
prev = 0;
i++;
}
else if (B[j] < A[i] && prev != 1)
{
prev = 1;
j++;
}
else if (A[i] == B[j])
{
if (prev != 1)
{
prev = 1;
j++;
}
else
{
prev = 0;
i++;
}
}
else
{
flag = false ;
break ;
}
}
return flag;
}
public static void Main()
{
int [] A = { 3, 5, 8 };
int [] B = { 2, 4, 6 };
int N = A.Length;
if (checkIfPossibleMerge(A, B, N))
{
Console.WriteLine( "Yes" );
}
else
{
Console.WriteLine( "No" );
}
}
}
|
Javascript
<script>
function checkIfPossibleMerge(A, B, N)
{
let i = 0;
let j = 0;
let prev = -1;
let flag = true ;
while (i < N && j < N)
{
if (A[i] < B[j] && prev != 0)
{
prev = 0;
i++;
}
else if (B[j] < A[i] && prev != 1)
{
prev = 1;
j++;
}
else if (A[i] == B[j])
{
if (prev != 1)
{
prev = 1;
j++;
}
else
{
prev = 0;
i++;
}
}
else
{
flag = false ;
break ;
}
}
return flag;
}
let A = [ 3, 5, 8 ];
let B = [ 2, 4, 6 ];
let N = A.length;
if (checkIfPossibleMerge(A, B, N))
{
document.write( "Yes" );
}
else
{
document.write( "No" );
}
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Approach 2: Dynamic Programming:
The given problem can be solved using a dynamic programming approach. We can create a 2D boolean table dp[][] of size (N+1)x(N+1) where dp[i][j] represents if it is possible to merge the first i elements of array A and the first j elements of array B with given conditions.
- The base case is dp[0][0] = true, as we can merge 0 elements from both arrays.
- For each (i,j) such that i>0 and j>0, we can calculate dp[i][j] as follows:
- If A[i-1] == B[j-1], then we can merge both the elements into the resulting array, and the previous element can be from either array. So, dp[i][j] = dp[i-1][j-1].
- If A[i-1] < B[j-1], then we can only merge the element A[i-1] into the resulting array if the previous element is from array B. So, dp[i][j] = dp[i][j-1].
- If A[i-1] > B[j-1], then we can only merge the element B[j-1] into the resulting array if the previous element is from array A. So, dp[i][j] = dp[i-1][j].
Finally, the answer is dp[N][N]. If dp[N][N] is true, it means it is possible to merge the entire arrays A and B with given conditions.
C++
#include <bits/stdc++.h>
using namespace std;
bool checkIfPossibleMerge( int A[], int B[], int N)
{
bool dp[N+1][N+1];
dp[0][0] = true ;
for ( int i = 1; i <= N; i++) {
dp[i][0] = (A[i-1] > A[i-2]) && dp[i-1][0];
dp[0][i] = (B[i-1] > B[i-2]) && dp[0][i-1];
}
for ( int i = 1; i <= N; i++) {
for ( int j = 1; j <= N; j++) {
if (A[i-1] == B[j-1]) {
dp[i][j] = dp[i-1][j-1];
}
else if (A[i-1] < B[j-1]) {
dp[i][j] = dp[i][j-1] && (A[i-1] > B[j-2]);
}
else {
dp[i][j] = dp[i-1][j] && (B[j-1] > A[i-2]);
}
}
}
return dp[N][N];
}
int main()
{
int A[3] = { 3, 5, 8 };
int B[3] = { 2, 4, 6 };
int N = sizeof (A) / sizeof (A[0]);
if (checkIfPossibleMerge(A, B, N)) {
cout << "Yes" ;
}
else {
cout << "No" ;
}
return 0;
}
|
Java
public class MergeArrays {
static boolean checkIfPossibleMerge( int [] A, int [] B, int N) {
boolean [][] dp = new boolean [N + 1 ][N + 1 ];
dp[ 0 ][ 0 ] = true ;
for ( int i = 1 ; i <= N; i++) {
dp[i][ 0 ] = (A[i - 1 ] > A[i - 2 ]) && dp[i - 1 ][ 0 ];
dp[ 0 ][i] = (B[i - 1 ] > B[i - 2 ]) && dp[ 0 ][i - 1 ];
}
for ( int i = 1 ; i <= N; i++) {
for ( int j = 1 ; j <= N; j++) {
if (A[i - 1 ] == B[j - 1 ]) {
dp[i][j] = dp[i - 1 ][j - 1 ];
} else if (A[i - 1 ] < B[j - 1 ]) {
dp[i][j] = dp[i][j - 1 ] && (A[i - 1 ] > B[j - 2 ]);
} else {
dp[i][j] = dp[i - 1 ][j] && (B[j - 1 ] > A[i - 2 ]);
}
}
}
return dp[N][N];
}
public static void main(String[] args) {
int [] A = { 3 , 5 , 8 };
int [] B = { 2 , 4 , 6 };
int N = A.length;
if (checkIfPossibleMerge(A, B, N)) {
System.out.println( "Yes" );
} else {
System.out.println( "No" );
}
}
}
|
Python3
def checkIfPossibleMerge(A, B, N):
dp = [[ False ] * (N + 1 ) for _ in range (N + 1 )]
dp[ 0 ][ 0 ] = True
for i in range ( 1 , N + 1 ):
dp[i][ 0 ] = (A[i - 1 ] > A[i - 2 ]) and dp[i - 1 ][ 0 ]
dp[ 0 ][i] = (B[i - 1 ] > B[i - 2 ]) and dp[ 0 ][i - 1 ]
for i in range ( 1 , N + 1 ):
for j in range ( 1 , N + 1 ):
if A[i - 1 ] = = B[j - 1 ]:
dp[i][j] = dp[i - 1 ][j - 1 ]
elif A[i - 1 ] < B[j - 1 ]:
dp[i][j] = dp[i][j - 1 ] and (A[i - 1 ] > B[j - 2 ])
else :
dp[i][j] = dp[i - 1 ][j] and (B[j - 1 ] > A[i - 2 ])
return dp[N][N]
if __name__ = = '__main__' :
A = [ 3 , 5 , 8 ]
B = [ 2 , 4 , 6 ]
N = len (A)
if checkIfPossibleMerge(A, B, N):
print ( "No" )
else :
print ( "Yes" )
|
C#
using System;
class Program
{
static bool CheckIfPossibleMerge( int [] A, int [] B, int N)
{
bool [,] dp = new bool [N + 1, N + 1];
dp[0, 0] = true ;
for ( int i = 1; i <= N; i++)
{
dp[i, 0] = (i > 1) && (A[i - 1] > A[i - 2]) && dp[i - 1, 0];
dp[0, i] = (i > 1) && (B[i - 1] > B[i - 2]) && dp[0, i - 1];
}
for ( int i = 1; i <= N; i++)
{
for ( int j = 1; j <= N; j++)
{
if (A[i - 1] == B[j - 1])
{
dp[i, j] = dp[i - 1, j - 1];
}
else if (A[i - 1] < B[j - 1])
{
dp[i, j] = dp[i, j - 1] && (A[i - 1] > B[j - 2]);
}
else
{
dp[i, j] = dp[i - 1, j] && (B[j - 1] > A[i - 2]);
}
}
}
return dp[N, N];
}
static void Main()
{
int [] A = { 3, 5, 8 };
int [] B = { 2, 4, 6 };
int N = A.Length;
if (CheckIfPossibleMerge(A, B, N))
{
Console.WriteLine( "No" );
}
else
{
Console.WriteLine( "Yes" );
}
}
}
|
Javascript
function checkIfPossibleMerge(A, B, N) {
let dp = new Array(N + 1).fill( false ).map(() => new Array(N + 1).fill( false ));
dp[0][0] = true ;
for (let i = 1; i <= N; i++) {
dp[i][0] = (A[i - 1] > A[i - 2]) && dp[i - 1][0];
dp[0][i] = (B[i - 1] > B[i - 2]) && dp[0][i - 1];
}
for (let i = 1; i <= N; i++) {
for (let j = 1; j <= N; j++) {
if (A[i - 1] === B[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
} else if (A[i - 1] < B[j - 1]) {
dp[i][j] = dp[i][j - 1] && (A[i - 1] > B[j - 2]);
} else {
dp[i][j] = dp[i - 1][j] && (B[j - 1] > A[i - 2]);
}
}
}
return dp[N][N];
}
let A = [3, 5, 8];
let B = [2, 4, 6];
let N = A.length;
if (checkIfPossibleMerge(A, B, N)) {
console.log( "No" );
} else {
console.log( "Yes" );
}
|
Time Complexity: O(N^2)
Auxiliary Space: O(N)
Last Updated :
21 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...