Print elements of an array according to the order defined by another array | set 2
Last Updated :
10 Feb, 2023
Given two arrays a1[] and a2[], print elements of a1 in such a way that the relative order among the elements will be the same as those are in a2. That is, elements which come before in the array a2[], print those elements first from the array a1[]. For the elements not present in a2, print them at last in sorted order.
It is also given that the number of elements in a2[] is smaller than or equal to the number of elements in a1[], and a2[] has all distinct elements.
Example:
Input: a1[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8}
a2[] = {2, 1, 8, 3}
Output: 2 2 1 1 8 8 3 5 6 7 9
Input: a1[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8}
a2[] = {1, 10, 11}
Output: 1 1 2 2 3 5 6 7 8 8 9
Simple Approach: We create a temporary array and a visited array where the temporary array is used to copy contents of a1[] to it and visited array is used to mark those elements in the temporary array which are copied to a1[]. Then sorting the temporary array and doing a binary search for every element of a2[] in a1[]. You can find the solution here.
Efficient Approach: We can print the elements of a1[] according to the order defined by a2[] using map in c++ in O(mlog(n)) time. We traverse through a1[] and store the frequency of every number in a map. Then we traverse through a2[] and check if the number is present in the map. If the number is present, then print it that many times and erase the number from the map. Print the rest of the numbers present in the map sequentially as numbers are stored in the map in sorted order.
Below is the implementation of the above approach:
C++
// A C++ program to print an array according
// to the order defined by another array
#include <bits/stdc++.h>
using namespace std;
// Function to print an array according
// to the order defined by another array
void print_in_order(int a1[], int a2[], int n, int m)
{
// Declaring map and iterator
map<int, int> mp;
map<int, int>::iterator itr;
// Store the frequency of each
// number of a1[] int the map
for (int i = 0; i < n; i++)
mp[a1[i]]++;
// Traverse through a2[]
for (int i = 0; i < m; i++) {
// Check whether number
// is present in map or not
if (mp.find(a2[i]) != mp.end()) {
itr = mp.find(a2[i]);
// Print that number that
// many times of its frequency
for (int j = 0; j < itr->second; j++)
cout << itr->first << " ";
mp.erase(a2[i]);
}
}
// Print those numbers that are not
// present in a2[]
for (itr = mp.begin(); itr != mp.end(); itr++) {
for (int j = 0; j < itr->second; j++)
cout << itr->first << " ";
}
cout << endl;
}
// Driver code
int main()
{
int a1[] = { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 };
int a2[] = { 2, 1, 8, 3 };
int n = sizeof(a1) / sizeof(a1[0]);
int m = sizeof(a2) / sizeof(a2[0]);
print_in_order(a1, a2, n, m);
return 0;
}
Java
/*package whatever //do not write package name here */
import java.util.*;
class GFG {
// Function to print an array according
// to the order defined by another array
static void print_in_order(int a1[], int a2[], int n, int m)
{
// Declaring map and iterator
HashMap<Integer, Integer> mp = new HashMap<>();
// Store the frequency of each
// number of a1[] int the map
for (int i = 0; i < n; i++)
mp.put(a1[i],mp.getOrDefault(a1[i],0)+1);
// Traverse through a2[]
for (int i = 0; i < m; i++) {
// Check whether number
// is present in map or not
if (mp.containsKey(a2[i])) {
// Print that number that
// many times of its frequency
for (int j = 0; j < mp.get(a2[i]); j++)
System.out.print(a2[i] + " ");
mp.remove(a2[i]);
}
}
// Print those numbers that are not
// present in a2[]
for (int i:mp.keySet()) {
for (int j = 0; j < mp.get(i); j++)
System.out.print(i + " ");
}
System.out.println();
}
public static void main (String[] args) {
int a1[] = { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 };
int a2[] = { 2, 1, 8, 3 };
int n = a1.length;
int m = a2.length;
print_in_order(a1, a2, n, m);
}
}
// This code is contributed by aadityaburujwale.
Python3
# A Python3 program to print an array according
# to the order defined by another array
# Function to print an array according
# to the order defined by another array
def print_in_order(a1, a2, n, m) :
# Declaring map and iterator
mp = dict.fromkeys(a1,0);
# Store the frequency of each
# number of a1[] int the map
for i in range(n) :
mp[a1[i]] += 1;
# Traverse through a2[]
for i in range(m) :
# Check whether number
# is present in map or not
if a2[i] in mp.keys() :
# Print that number that
# many times of its frequency
for j in range(mp[a2[i]]) :
print(a2[i],end=" ");
del(mp[a2[i]]);
# Print those numbers that are not
# present in a2[]
for key,value in mp.items() :
for j in range(value) :
print(key,end=" ");
print();
# Driver code
if __name__ == "__main__" :
a1 = [ 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 ];
a2 = [ 2, 1, 8, 3 ];
n =len(a1);
m = len(a2);
print_in_order(a1, a2, n, m);
# This code is contributed by AnkitRai01
C#
using System;
using System.Collections.Generic;
class GFG {
static void PrintInOrder(int[] a1, int[] a2)
{
Dictionary<int, int> dict
= new Dictionary<int, int>();
// Store the frequency of each
// number of a1[] int the dictionary
for (int i = 0; i < a1.Length; i++) {
if (dict.ContainsKey(a1[i]))
dict[a1[i]]++;
else
dict.Add(a1[i], 1);
}
// Traverse through a2[]
for (int i = 0; i < a2.Length; i++) {
// Check whether number
// is present in dictionary or not
if (dict.ContainsKey(a2[i])) {
// Print that number that
// many times of its frequency
for (int j = 0; j < dict[a2[i]]; j++)
Console.Write(a2[i] + " ");
dict.Remove(a2[i]);
}
}
// Print those numbers that are not
// present in a2[]
foreach(var pair in dict)
{
for (int j = 0; j < pair.Value; j++)
Console.Write(pair.Key + " ");
}
Console.WriteLine();
}
static void Main(string[] args)
{
int[] a1 = { 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 };
int[] a2 = { 2, 1, 8, 3 };
PrintInOrder(a1, a2);
}
}
JavaScript
<script>
// A JavaScript program to print an array according
// to the order defined by another array
// Function to print an array according
// to the order defined by another array
function print_in_order(a1, a2, n, m){
// Declaring map and iterator
let mp = new Map();
// Store the frequency of each
// number of a1[] int the map
for(let i=0;i<n;i++){
if(mp.has(a1[i]))
mp.set(a1[i],mp.get(a1[i])+1);
else
mp.set(a1[i],1);
}
// Traverse through a2[]
for(let i=0;i<m;i++){
// Check whether number
// is present in map or not
if(mp.has(a2[i])){
// Print that number that
// many times of its frequency
for(let j=0;j<mp.get(a2[i]);j++)
document.write(a2[i]," ");
mp.delete(a2[i]);
}
}
// Print those numbers that are not
// present in a2[]
for(let [key,value] of mp)
for(let j=0;j<value;j++)
document.write(key," ");
document.write("</br>");
}
// Driver code
let a1 = [ 2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8 ];
let a2 = [ 2, 1, 8, 3 ];
let n = a1.length;
let m = a2.length;
print_in_order(a1, a2, n, m);
// This code is contributed by shinjanpatra
</script>
Output: 2 2 1 1 8 8 3 5 6 7 9
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In 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
4 min read
Sorting Algorithms A 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