Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Check if two sorted arrays can be merged to form a sorted array with no adjacent pair from the same array
Next article icon

Generate all possible sorted arrays from alternate elements of two given sorted arrays

Last Updated : 11 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two sorted arrays A and B, generate all possible arrays such that the first element is taken from A then from B then from A, and so on in increasing order till the arrays are exhausted. The generated arrays should end with an element from B.

Example:

   A = {10, 15, 25}  B = {1, 5, 20, 30}    The resulting arrays are:    10 20    10 20 25 30    10 30    15 20    15 20 25 30    15 30    25 30

Method 1: The idea is to use recursion. In the recursive function, a flag is passed to indicate whether current element in output should be taken from 'A' or 'B'.

C++
#include<bits/stdc++.h> using namespace std;  void printArr(int arr[], int n);  /* Function to generates and prints all sorted arrays from alternate elements of    'A[i..m-1]' and 'B[j..n-1]'    If 'flag' is true, then current element is to be included from A otherwise    from B.    'len' is the index in output array C[]. We print output  array  each time    before including a character from A only if length of output array is    greater than 0. We try than all possible combinations */ void generateUtil(int A[], int B[], int C[], int i, int j, int m, int n,                   int len, bool flag) {     if (flag) // Include valid element from A     {         // Print output if there is at least one 'B' in output array 'C'         if (len)             printArr(C, len+1);          // Recur for all elements of A after current index         for (int k = i; k < m; k++)         {             if (!len)             {                 /* this block works for the very first call to include                      the first element in the output array */                 C[len] = A[k];                  // don't increment lem as B is included yet                 generateUtil(A, B, C, k+1, j, m, n, len, !flag);             }             else      /* include valid element from A and recur */             {                 if (A[k] > C[len])                 {                     C[len+1] = A[k];                     generateUtil(A, B, C, k+1, j, m, n, len+1, !flag);                 }             }         }     }     else   /* Include valid element from B and recur */     {         for (int l = j; l < n; l++)         {             if (B[l] > C[len])             {                 C[len+1] = B[l];                 generateUtil(A, B, C, i, l+1, m, n, len+1, !flag);             }         }     } }  /* Wrapper function */ void generate(int A[], int B[], int m, int n) {     int C[m+n];    /* output array */     generateUtil(A, B, C, 0, 0, m, n, 0, true); }  // A utility function to print an array void printArr(int arr[], int n) {     for (int i = 0; i < n; i++)         cout << arr[i] << " ";     cout << endl; }  // Driver program int main() {     int A[] = {10, 15, 25};     int B[] = {5, 20, 30};     int n = sizeof(A)/sizeof(A[0]);     int m = sizeof(B)/sizeof(B[0]);     generate(A, B, n, m);     return 0; } 
Java
import java.io.*;  public class GenerateArrays {      /* Function to generates and prints all sorted arrays        from alternate elements of 'A[i..m-1]' and        'B[j..n-1]' If 'flag' is true, then current element        is to be included from A otherwise from B. 'len' is        the index in output array C[]. We print output array        each time before including a character from A only if        length of output array is greater than 0. We try than        all possible combinations */     void generateUtil(int A[], int B[], int C[], int i,                       int j, int m, int n, int len,                       boolean flag)     {         if (flag) // Include valid element from A         {             // Print output if there is at least one 'B' in             // output array 'C'             if (len != 0)                 printArr(C, len + 1);              // Recur for all elements of A after current             // index             for (int k = i; k < m; k++) {                 if (len == 0) {                     /* this block works for the very first                     call to include                     the first element in the output array */                     C[len] = A[k];                      // don't increment lem as B is included                     // yet                     generateUtil(A, B, C, k + 1, j, m, n,                                  len, !flag);                 }                  /* include valid element from A and recur */                 else if (A[k] > C[len]) {                     C[len + 1] = A[k];                     generateUtil(A, B, C, k + 1, j, m, n,                                  len + 1, !flag);                 }             }         }          /* Include valid element from B and recur */         else {             for (int l = j; l < n; l++) {                 if (B[l] > C[len]) {                     C[len + 1] = B[l];                     generateUtil(A, B, C, i, l + 1, m, n,                                  len + 1, !flag);                 }             }         }     }      /* Wrapper function */     void generate(int A[], int B[], int m, int n)     {         int C[] = new int[m + n];          /* output array */         generateUtil(A, B, C, 0, 0, m, n, 0, true);     }      // A utility function to print an array     void printArr(int arr[], int n)     {         for (int i = 0; i < n; i++)             System.out.print(arr[i] + " ");         System.out.println("");     }      public static void main(String[] args)     {         GenerateArrays generate = new GenerateArrays();         int A[] = { 10, 15, 25 };         int B[] = { 5, 20, 30 };         int n = A.length;         int m = B.length;         generate.generate(A, B, n, m);     } }  // This code has been contributed by Mayank Jaiswal 
Python3
# A utility function to print an array def printArr(arr,n):      for i in range(n):         print(arr[i] , " ",end="")     print()   ''' Function to generates and prints all     sorted arrays from alternate elements of    'A[i..m-1]' and 'B[j..n-1]'    If 'flag' is true, then current element    is to be included from A otherwise    from B.    'len' is the index in output array C[].     We print output  array  each time    before including a character from A    only if length of output array is    greater than 0. We try than all possible combinations ''' def generateUtil(A,B,C,i,j,m,n,len,flag):      if (flag): # Include valid element from A              # Print output if there is at         # least one 'B' in output array 'C'         if (len):             printArr(C, len+1)           # Recur for all elements of         # A after current index         for k in range(i,m):                      if ( not len):                              ''' this block works for the                     very first call to include                     the first element in the output array '''                 C[len] = A[k]                   # don't increment lem                 # as B is included yet                 generateUtil(A, B, C, k+1, j, m, n, len,  not flag)                          else:                      # include valid element from A and recur                  if (A[k] > C[len]):                                      C[len+1] = A[k]                     generateUtil(A, B, C, k+1, j, m, n, len+1, not flag)                           else:              # Include valid element from B and recur         for l in range(j,n):                      if (B[l] > C[len]):                              C[len+1] = B[l]                 generateUtil(A, B, C, i, l+1, m, n, len+1, not flag)               # Wrapper function  def generate(A,B,m,n):      C=[]    #output array      for i in range(m+n+1):         C.append(0)     generateUtil(A, B, C, 0, 0, m, n, 0, True)     # Driver program  A = [10, 15, 25] B = [5, 20, 30] n = len(A) m = len(B)  generate(A, B, n, m)  # This code is contributed # by Anant Agarwal. 
C#
// C# Program to generate all possible // sorted arrays from alternate elements // of two given sorted arrays using System;  class GenerateArrays {  /* Function to generates and prints    all sorted arrays from alternate     elements of 'A[i..m-1]' and 'B[j..n-1]'     If 'flag' is true, then current element    is to be included from A otherwise    from B.     'len' is the index in output array     C[]. We print output array each     time before including a character     from A only if length of output array     is greater than 0. We try than all     possible combinations */    public virtual void generateUtil(int[] A, int[] B,                                     int[] C, int i,                                      int j, int m, int n,                                     int len, bool flag) {          // Include valid      // element from A                                        if (flag)      {                  // Print output if there is         // at least one 'B' in          // output array 'C'          if (len != 0) {                          printArr(C, len + 1);         }          // Recur for all elements         // of A after current index          for (int k = i; k < m; k++) {                          if (len == 0) {                                  /* this block works for the                     very first call to include                     the first element in the                     output array */                 C[len] = A[k];                  // don't increment lem                  // as B is included yet                  generateUtil(A, B, C, k + 1, j,                              m, n, len, !flag);             }              // include valid element             // from A and recur              else if (A[k] > C[len]) {                                  C[len + 1] = A[k];                 generateUtil(A, B, C, k + 1, j,                          m, n, len + 1, !flag);             }         }     }      // Include valid element     // from B and recur      else {         for (int l = j; l < n; l++) {             if (B[l] > C[len]) {                 C[len + 1] = B[l];                 generateUtil(A, B, C, i, l + 1,                          m, n, len + 1, !flag);             }         }     } }  // Wrapper function  public virtual void generate(int[] A, int[] B,                                int m, int n) {     int[] C = new int[m + n];      // output array      generateUtil(A, B, C, 0, 0, m, n, 0, true); }  // A utility function to print an array  public virtual void printArr(int[] arr, int n) {          for (int i = 0; i < n; i++) {         Console.Write(arr[i] + " ");     }     Console.WriteLine(""); }  // Driver Code public static void Main(string[] args) {          GenerateArrays generate = new GenerateArrays();          int[] A = new int[] {10, 15, 25};     int[] B = new int[] {5, 20, 30};          int n = A.Length;     int m = B.Length;     generate.generate(A, B, n, m); } }  // This code is contributed by Shrikant13 
PHP
<?php   /* Function to generates and prints all  sorted arrays from alternate elements of 'A[i..m-1]' and 'B[j..n-1]' If 'flag' is true, then current element is to be included from A otherwise from B. 'len' is the index in output array C[].  We print output array each time before including a character from A only if length  of output array is greater than 0. We try than all possible combinations */ function generateUtil(&$A, &$B, &$C, $i, $j,                        $m, $n, $len, $flag) {     if ($flag) // Include valid element from A     {         // Print output if there is at least         // one 'B' in output array 'C'         if ($len)             printArr($C, $len + 1);          // Recur for all elements of A          // after current index         for ($k = $i; $k < $m; $k++)         {             if (!$len)             {                 /* this block works for the very                  first call to include the first                  element in the output array */                 $C[$len] = $A[$k];                  // don't increment lem as B                 // is included yet                 generateUtil($A, $B, $C, $k + 1,                              $j, $m, $n, $len, !$flag);             }             else     /* include valid element                         from A and recur */             {                 if ($A[$k] > $C[$len])                 {                     $C[$len + 1] = $A[$k];                     generateUtil($A, $B, $C, $k + 1, $j,                                   $m, $n, $len + 1, !$flag);                 }             }         }     }     else /* Include valid element              from B and recur */     {         for ($l = $j; $l < $n; $l++)         {             if ($B[$l] > $C[$len])             {                 $C[$len + 1] = $B[$l];                 generateUtil($A, $B, $C, $i, $l + 1,                              $m, $n, $len + 1, !$flag);             }         }     } }  /* Wrapper function */ function generate(&$A, &$B, $m, $n) {     $C = array_fill(0, ($m + $n), NULL); /* output array */     generateUtil($A, $B, $C, 0, 0, $m, $n, 0, true); }  // A utility function to print an array function printArr(&$arr, $n) {     for ($i = 0; $i < $n; $i++)         echo $arr[$i] . " ";     echo "\n"; }  // Driver Code $A = array(10, 15, 25); $B = array(5, 20, 30); $n = sizeof($A); $m = sizeof($B); generate($A, $B, $n, $m);  // This code is contributed by ChitraNayal ?> 
JavaScript
<script>     /*      * Function to generates and prints all sorted arrays from alternate elements of      * 'A[i..m-1]' and 'B[j..n-1]' If 'flag' is true, then current element is to be      * included from A otherwise from B. 'len' is the index in output array C. We      * print output array each time before including a character from A only if      * length of output array is greater than 0. We try than all possible      * combinations      */     function generateUtil(A , B , C , i , j , m , n , len,  flag) {         if (flag) // Include valid element from A         {             // Print output if there is at least one 'B' in output array 'C'             if (len != 0)                 printArr(C, len + 1);              // Recur for all elements of A after current index             for (var k = i; k < m; k++) {                 if (len == 0) {                     /*                      * this block works for the very first call to include the first element in the                      * output array                      */                     C[len] = A[k];                      // don't increment lem as B is included yet                     generateUtil(A, B, C, k + 1, j, m, n, len, !flag);                 }                  /* include valid element from A and recur */                 else if (A[k] > C[len]) {                     C[len + 1] = A[k];                     generateUtil(A, B, C, k + 1, j, m, n, len + 1, !flag);                 }             }         }          /* Include valid element from B and recur */         else {             for (var l = j; l < n; l++) {                 if (B[l] > C[len]) {                     C[len + 1] = B[l];                     generateUtil(A, B, C, i, l + 1, m, n, len + 1, !flag);                 }             }         }     }      /* Wrapper function */     function generate(A , B , m , n) {         var C = Array(m + n).fill(0);          /* output array */         generateUtil(A, B, C, 0, 0, m, n, 0, true);     }      // A utility function to print an array     function printArr(arr , n) {         for (i = 0; i < n; i++)             document.write(arr[i] + " ");         document.write("<br/>");     }                    var A = [ 10, 15, 25 ];         var B = [ 5, 20, 30 ];         var n = A.length;         var m = B.length;         generate(A, B, n, m);  // This code contributed by gauravrajput1 </script> 

Output
10 20   10 20 25 30   10 30   15 20   15 20 25 30   15 30   25 30   

Time Complexity: O(N2)
Auxiliary Space: O(M+N)

\
 


Next Article
Check if two sorted arrays can be merged to form a sorted array with no adjacent pair from the same array

G

Gaurav Ahirwar
Improve
Article Tags :
  • Recursion
  • DSA
  • Arrays
Practice Tags :
  • Arrays
  • Recursion

Similar Reads

  • Merging elements of two different arrays alternatively in third array
    Given two arrays arr1[] and arr2[], we need to combine two arrays in such a way that the combined array has alternate elements of both. If one array has extra element, then these elements are appended at the end of the combined array. Input : arr1[] = {1, 2, 3, 4, 5, 6} arr2[] = {11, 22, 33, 44}Outp
    7 min read
  • Count of possible unique arrays after swapping elements at same index of given Arrays
    Given two arrays arr1[] and arr2[] with distinct elements of size N.The task is to count the total number of possible combinations after swapping elements at the same index of both the arrays such that there are no duplicates in both the arrays after performing the operation. Examples: Input: arr1[]
    12 min read
  • Rearrange an array to make similar indexed elements different from that of another array
    Given two sorted arrays A[] and B[] consisting of N distinct integers, the task is to rearrange the elements of array B[] such that, for every ith index, A[i] is not equal to B[i]. If multiple such arrangements exist, print any one of them. If no such arrangement exists, print -1. Examples: Input: A
    7 min read
  • 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]
    15+ min read
  • Count number of common elements between a sorted array and a reverse sorted array
    Given two arrays consisting of N distinct integers such that the array A[] and B[] are sorted in ascending and descending order respectively, the task is to find the number of values common in both arrays. Examples: Input: A[] = {1, 10, 100}, B[] = {200, 20, 2}Output: 0 Input: A[] = {2, 4, 5, 8, 12,
    15+ min read
  • Find sorted order of Array after replacing digits with their given alternate
    Given an array A[] containing N integers and another array M[] containing alternate values of all digits from 0 to 9 (i.e; M[i] = j means, j is an alternate value of i( 0 ≤ i, j ≤ 9)), Perform following operations on the array: Replace all the digits of all elements of array A[] with their alternate
    9 min read
  • Check if it is possible to sort the array without swapping adjacent elements
    Given an array arr[] of size N, check if it is possible to sort arr[] without swapping adjacent elements. In other words, check if it is possible to sort arr[] by swapping elements but swapping two consecutive element is not allowed. Examples: Input: N = 4, arr[] = {2, 3, 1, 4}Output: YESExplanation
    5 min read
  • Sort an array having first N elements sorted and last M elements are unsorted
    Given two positive integers, N and M, and an array arr[ ] consisting of (N + M) integers such that the first N elements are sorted in ascending order and the last M elements are unsorted, the task is to sort the given array in ascending order. Examples: Input: N = 3, M = 5, arr[] = {2, 8, 10, 17, 15
    13 min read
  • Count of all possible Arrays such that each array element can be over the range [1, arr[i]]
    Given an array arr[] consisting of N positive integers, the task is to find the number of all possible arrays such that each array element can be over the range [1, arr[i]] all elements in the newly constructed array must be pairwise distinct. Examples: Input: arr[] = {5}Output: 5Explanation:All pos
    5 min read
  • Check if given array is almost sorted (elements are at-most one position away)
    Given an array with n distinct elements. An array is said to be almost sorted (non-decreasing) if any of its elements can occur at a maximum of 1 distance away from their original places in the sorted array. We need to find whether the given array is almost sorted or not.Examples: Input : arr[] = {1
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences