Check if two sorted arrays can be merged to form a sorted array with no adjacent pair from the same array
Last Updated :
23 Jul, 2025
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++
// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to check if it is possible to merge
// the two given arrays with given conditions
bool checkIfPossibleMerge(int A[], int B[], int N)
{
// Stores index of
// the array A[]
int i = 0;
// Stores index of
// the array B[]
int j = 0;
// Check if the previous element are from
// the array A[] or from the array B[]
int prev = -1;
// Check if it is possible to merge the two
// given sorted arrays with given conditions
int flag = 1;
// Traverse both the arrays
while (i < N && j < N) {
// If A[i] is less than B[j] and
// previous element are not from A[]
if (A[i] < B[j] && prev != 0) {
// Update prev
prev = 0;
// Update i
i++;
}
// If B[j] is less than A[i] and
// previous element are not from B[]
else if (B[j] < A[i] && prev != 1) {
// Update prev
prev = 1;
// Update j
j++;
}
// If A[i] equal to B[j]
else if (A[i] == B[j]) {
// If previous element
// are not from B[]
if (prev != 1) {
// Update prev
prev = 1;
// Update j
j++;
}
// If previous element is
// not from A[]
else {
// Update prev
prev = 0;
// Update i
i++;
}
}
// If it is not possible to merge two
// sorted arrays with given conditions
else {
// Update flag
flag = 0;
break;
}
}
return flag;
}
// Driver Code
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
// Java program to implement
// the above approach
import java.io.*;
class GFG{
// Function to check if it is possible to merge
// the two given arrays with given conditions
static boolean checkIfPossibleMerge(int[] A, int[] B,
int N)
{
// Stores index of
// the array A[]
int i = 0;
// Stores index of
// the array B[]
int j = 0;
// Check if the previous element are from
// the array A[] or from the array B[]
int prev = -1;
// Check if it is possible to merge the two
// given sorted arrays with given conditions
boolean flag = true;
// Traverse both the arrays
while (i < N && j < N)
{
// If A[i] is less than B[j] and
// previous element are not from A[]
if (A[i] < B[j] && prev != 0)
{
// Update prev
prev = 0;
// Update i
i++;
}
// If B[j] is less than A[i] and
// previous element are not from B[]
else if (B[j] < A[i] && prev != 1)
{
// Update prev
prev = 1;
// Update j
j++;
}
// If A[i] equal to B[j]
else if (A[i] == B[j])
{
// If previous element
// are not from B[]
if (prev != 1)
{
// Update prev
prev = 1;
// Update j
j++;
}
// If previous element is
// not from A[]
else
{
// Update prev
prev = 0;
// Update i
i++;
}
}
// If it is not possible to merge two
// sorted arrays with given conditions
else
{
// Update flag
flag = false;
break;
}
}
return flag;
}
// Driver Code
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");
}
}
}
// This code is contributed by akhilsaini
Python3
# Python3 program to implement
# the above approach
# Function to check if it is possible
# to merge the two given arrays with
# given conditions
def checkIfPossibleMerge(A, B, N):
# Stores index of
# the array A[]
i = 0
# Stores index of
# the array B[]
j = 0
# Check if the previous element
# are from the array A[] or from
# the array B[]
prev = -1
# Check if it is possible to merge
# the two given sorted arrays with
# given conditions
flag = 1
# Traverse both the arrays
while (i < N and j < N):
# If A[i] is less than B[j] and
# previous element are not from A[]
if (A[i] < B[j] and prev != 0):
# Update prev
prev = 0
# Update i
i += 1
# If B[j] is less than A[i] and
# previous element are not from B[]
elif (B[j] < A[i] and prev != 1):
# Update prev
prev = 1
# Update j
j += 1
# If A[i] equal to B[j]
elif (A[i] == B[j]):
# If previous element
# are not from B[]
if (prev != 1):
# Update prev
prev = 1
# Update j
j += 1
# If previous element is
# not from A[]
else:
# Update prev
prev = 0
# Update i
i += 1
# If it is not possible to merge two
# sorted arrays with given conditions
else:
# Update flag
flag = 0
break
return flag
# Driver Code
if __name__ == '__main__':
A = [ 3, 5, 8 ]
B = [ 2, 4, 6 ]
N = len(A)
if (checkIfPossibleMerge(A, B, N)):
print("Yes")
else:
print("No")
# This code is contributed by akhilsaini
C#
// C# program to implement
// the above approach
using System;
class GFG{
// Function to check if it is possible to merge
// the two given arrays with given conditions
static bool checkIfPossibleMerge(int[] A, int[] B,
int N)
{
// Stores index of
// the array A[]
int i = 0;
// Stores index of
// the array B[]
int j = 0;
// Check if the previous element are
// from the array A[] or from the
// array B[]
int prev = -1;
// Check if it is possible to merge
// the two given sorted arrays with
// given conditions
bool flag = true;
// Traverse both the arrays
while (i < N && j < N)
{
// If A[i] is less than B[j] and
// previous element are not from A[]
if (A[i] < B[j] && prev != 0)
{
// Update prev
prev = 0;
// Update i
i++;
}
// If B[j] is less than A[i] and
// previous element are not from B[]
else if (B[j] < A[i] && prev != 1)
{
// Update prev
prev = 1;
// Update j
j++;
}
// If A[i] equal to B[j]
else if (A[i] == B[j])
{
// If previous element
// are not from B[]
if (prev != 1)
{
// Update prev
prev = 1;
// Update j
j++;
}
// If previous element is
// not from A[]
else
{
// Update prev
prev = 0;
// Update i
i++;
}
}
// If it is not possible to merge two
// sorted arrays with given conditions
else
{
// Update flag
flag = false;
break;
}
}
return flag;
}
// Driver Code
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");
}
}
}
// This code is contributed by akhilsaini
JavaScript
<script>
// Javascript program to implement
// the above approach
// Function to check if it is possible to merge
// the two given arrays with given conditions
function checkIfPossibleMerge(A, B, N)
{
// Stores index of
// the array A[]
let i = 0;
// Stores index of
// the array B[]
let j = 0;
// Check if the previous element are from
// the array A[] or from the array B[]
let prev = -1;
// Check if it is possible to merge the two
// given sorted arrays with given conditions
let flag = true;
// Traverse both the arrays
while (i < N && j < N)
{
// If A[i] is less than B[j] and
// previous element are not from A[]
if (A[i] < B[j] && prev != 0)
{
// Update prev
prev = 0;
// Update i
i++;
}
// If B[j] is less than A[i] and
// previous element are not from B[]
else if (B[j] < A[i] && prev != 1)
{
// Update prev
prev = 1;
// Update j
j++;
}
// If A[i] equal to B[j]
else if (A[i] == B[j])
{
// If previous element
// are not from B[]
if (prev != 1)
{
// Update prev
prev = 1;
// Update j
j++;
}
// If previous element is
// not from A[]
else
{
// Update prev
prev = 0;
// Update i
i++;
}
}
// If it is not possible to merge two
// sorted arrays with given conditions
else
{
// Update flag
flag = false;
break;
}
}
return flag;
}
// Driver Code
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");
}
// This code is contributed by splevel62.
</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;
// Function to check if it is possible to merge
// the two given arrays with given conditions
bool checkIfPossibleMerge(int A[], int B[], int N)
{
// Create a 2D boolean table
bool dp[N+1][N+1];
// Base case
dp[0][0] = true;
// Initialize the first row and column
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];
}
// Fill the remaining table
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];
}
// Driver Code
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 {
// Function to check if it is possible to merge
// the two given arrays with given conditions
static boolean checkIfPossibleMerge(int[] A, int[] B, int N) {
// Create a 2D boolean table
boolean[][] dp = new boolean[N + 1][N + 1];
// Base case
dp[0][0] = true;
// Initialize the first row and column
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];
}
// Fill the remaining table
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];
}
// Driver Code
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):
# Create a 2D boolean table
dp = [[False]*(N+1) for _ in range(N+1)]
# Base case
dp[0][0] = True
# Initialize the first row and column
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]
# Fill the remaining table
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]
# Driver Code
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
{
// Function to check if it is possible to merge
// the two given arrays with given conditions
static bool CheckIfPossibleMerge(int[] A, int[] B, int N)
{
// Create a 2D boolean table
bool[,] dp = new bool[N + 1, N + 1];
// Base case
dp[0, 0] = true;
// Initialize the first row and column
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];
}
// Fill the remaining table
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];
}
// Driver Code
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) {
// Create a 2D boolean table
let dp = new Array(N + 1).fill(false).map(() => new Array(N + 1).fill(false));
// Base case
dp[0][0] = true;
// Initialize the first row and column
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];
}
// Fill the remaining table
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];
}
// Driver Code
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)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem