Given two integer arrays a[] and b[], return an array containing all elements common to both arrays in sorted order.
If an element appears multiple times in both arrays, it should appear in the output as many times as it is common to both arrays.
Input: a[] = [3, 4, 2, 2, 4] , b[] = [3, 2, 2, 7]
Output: [2, 2, 3]
Explanation: The common elements in sorted order are 2, 2, 3.Input: a[] = [3, 6, 1, 7, 9, 8, 2, 2] , b[] = [9, 7, 3, 4, 9]
Output: [3, 7, 9]
Explanation: The common elements in sorted order are 3, 7, 9.
Table of Content
Naive Approach - Using Nested Loops O(n*m) Time and O(m) Space
Compare each element of the first array with every element of the second array and match equal elements one by one.
- Create a boolean array to mark matched elements in the second array.
- Traverse the first array and search for the first unmatched occurrence of each element in the second array.
- If found, add it to the answer and mark it as matched.
- Sort the answer before returning it.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> commonElements(vector<int>& a, vector<int>& b) {
int n = a.size(), m = b.size();
vector<int> ans;
vector<bool> used(m, false);
// Compare every element of a with every element of b
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// Match only unused equal elements
if (!used[j] && a[i] == b[j]) {
ans.push_back(a[i]);
used[j] = true;
break;
}
}
}
// Return elements in sorted order
sort(ans.begin(), ans.end());
return ans;
}
int main() {
vector<int> a = {3, 4, 2, 2, 4};
vector<int> b = {3, 2, 2, 7};
vector<int> result = commonElements(a, b);
cout << "[";
for (int i = 0; i < result.size(); i++) {
cout << result[i];
if (i != result.size() - 1)
cout << ", ";
}
cout << "]" << endl;
return 0;
}
import java.util.ArrayList;
import java.util.Arrays;
public class GFG {
public static ArrayList<Integer> commonElements(int[] a, int[] b) {
int n = a.length, m = b.length;
ArrayList<Integer> ans = new ArrayList<>();
boolean[] used = new boolean[m];
Arrays.fill(used, false);
// Compare every element of a with every element of b
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// Match only unused equal elements
if (!used[j] && a[i] == b[j]) {
ans.add(a[i]);
used[j] = true;
break;
}
}
}
// Return elements in sorted order
ans.sort(null);
return ans;
}
public static void main(String[] args) {
int[] a = {3, 4, 2, 2, 4};
int[] b = {3, 2, 2, 7};
ArrayList<Integer> result = commonElements(a, b);
System.out.print("[");
for (int i = 0; i < result.size(); i++) {
System.out.print(result.get(i));
if (i!= result.size() - 1)
System.out.print(", ");
}
System.out.println("]");
}
}
def commonElements(a, b):
n = len(a)
m = len(b)
ans = []
used = [False] * m
# Compare every element of a with every element of b
for i in range(n):
for j in range(m):
# Match only unused equal elements
if not used[j] and a[i] == b[j]:
ans.append(a[i])
used[j] = True
break
# Return elements in sorted order
ans.sort()
return ans
if __name__ == '__main__':
a = [3, 4, 2, 2, 4]
b = [3, 2, 2, 7]
result = commonElements(a, b)
print('[', end='')
for i in range(len(result)):
print(result[i], end='' if i == len(result) - 1 else ', ')
print(']')
using System;
using System.Collections.Generic;
using System.Linq;
public class GFG {
public static List<int> commonElements(int[] a, int[] b) {
int n = a.Length, m = b.Length;
List<int> ans = new List<int>();
bool[] used = new bool[m];
// Compare every element of a with every element of b
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// Match only unused equal elements
if (!used[j] && a[i] == b[j]) {
ans.Add(a[i]);
used[j] = true;
break;
}
}
}
// Return elements in sorted order
ans.Sort();
return ans;
}
public static void Main() {
int[] a = {3, 4, 2, 2, 4};
int[] b = {3, 2, 2, 7};
List<int> result = commonElements(a, b);
Console.Write("[");
for (int i = 0; i < result.Count; i++)
{
Console.Write(result[i]);
if (i!= result.Count - 1)
Console.Write(", ");
}
Console.WriteLine("]");
}
}
function commonElements(a, b) {
let n = a.length, m = b.length;
let ans = [];
let used = Array(m).fill(false);
// Compare every element of a with every element of b
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
// Match only unused equal elements
if (!used[j] && a[i] === b[j]) {
ans.push(a[i]);
used[j] = true;
break;
}
}
}
// Return elements in sorted order
ans.sort((x, y) => x - y);
return ans;
}
let a = [3, 4, 2, 2, 4];
let b = [3, 2, 2, 7];
let result = commonElements(a, b);
console.log('[' + result.join(', ') + ']');
Output
[2, 2, 3]
Expected Approach - Using Frequency Map O((n + m)* log (n+m) Time and O(n+m) Space
Store the frequency of elements in both arrays, then use the common frequencies to construct the answer in sorted order.
- Store the frequency of elements from both arrays in two ordered maps.
- Traverse the first map and, for each common element, store the minimum of the two frequencies.
- Traverse the resulting map and add each element to the answer according to its frequency.
#include <iostream>
#include <vector>
#include <map>
using namespace std;
vector<int> commonElements(vector<int>& a, vector<int>& b) {
vector<int> ans;
// Maps to store element frequencies
map<int, int> m1, m2, m3;
// Count frequencies in first array
for (int x : a) {
m1[x]++;
}
// Count frequencies in second array
for (int x : b) {
m2[x]++;
}
// Store common elements with minimum frequency
for (auto p : m1) {
if (m2.count(p.first)) {
m3[p.first] = min(p.second, m2[p.first]);
}
}
// Add elements to the answer
for (auto p : m3) {
for (int i = 0; i < p.second; i++) {
ans.push_back(p.first);
}
}
return ans;
}
int main() {
vector<int> a = {3, 4, 2, 2, 4};
vector<int> b = {3, 2, 2, 7};
vector<int> ans = commonElements(a, b);
cout << "[";
for (int i = 0; i < ans.size(); i++) {
cout << ans[i];
if (i != ans.size() - 1)
cout << ", ";
}
cout << "]" << endl;
return 0;
}
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;
public class GFG {
public static ArrayList<Integer> commonElements(int[] a, int[] b) {
ArrayList<Integer> ans = new ArrayList<>();
// Maps to store element frequencies
Map<Integer, Integer> m1 = new TreeMap<>();
Map<Integer, Integer> m2 = new TreeMap<>();
Map<Integer, Integer> m3 = new TreeMap<>();
// Count frequencies in first array
for (int x : a) {
m1.put(x, m1.getOrDefault(x, 0) + 1);
}
// Count frequencies in second array
for (int x : b) {
m2.put(x, m2.getOrDefault(x, 0) + 1);
}
// Store common elements with minimum frequency
for (Map.Entry<Integer, Integer> p : m1.entrySet()) {
if (m2.containsKey(p.getKey())) {
m3.put(p.getKey(), Math.min(p.getValue(), m2.get(p.getKey())));
}
}
// Add elements to the answer
for (Map.Entry<Integer, Integer> p : m3.entrySet()) {
for (int i = 0; i < p.getValue(); i++) {
ans.add(p.getKey());
}
}
return ans;
}
public static void main(String[] args) {
int[] a = {3, 4, 2, 2, 4};
int[] b = {3, 2, 2, 7};
ArrayList<Integer> ans = commonElements(a, b);
System.out.println(ans);
}
}
def commonElements(a, b):
ans = []
# Maps to store element frequencies
m1 = {}
m2 = {}
m3 = {}
# Count frequencies in first array
for x in a:
if x in m1:
m1[x] += 1
else:
m1[x] = 1
# Count frequencies in second array
for x in b:
if x in m2:
m2[x] += 1
else:
m2[x] = 1
# Store common elements with minimum frequency
for key in m1:
if key in m2:
m3[key] = min(m1[key], m2[key])
# Add elements to the answer
for key in sorted(m3):
for _ in range(m3[key]):
ans.append(key)
return ans
if __name__ == "__main__":
a = [3, 4, 2, 2, 4]
b = [3, 2, 2, 7]
ans = commonElements(a, b)
print("[" + ", ".join(map(str, ans)) + "]")
using System;
using System.Collections.Generic;
public class GFG {
public static List<int> commonElements(int[] a, int[] b) {
List<int> ans = new List<int>();
// Maps to store element frequencies
SortedDictionary<int, int> m1 = new SortedDictionary<int, int>();
SortedDictionary<int, int> m2 = new SortedDictionary<int, int>();
SortedDictionary<int, int> m3 = new SortedDictionary<int, int>();
// Count frequencies in first array
foreach (int x in a) {
if (m1.ContainsKey(x))
m1[x]++;
else
m1[x] = 1;
}
// Count frequencies in second array
foreach (int x in b) {
if (m2.ContainsKey(x))
m2[x]++;
else
m2[x] = 1;
}
// Store common elements with minimum frequency
foreach (var p in m1) {
if (m2.ContainsKey(p.Key)) {
m3[p.Key] = Math.Min(p.Value, m2[p.Key]);
}
}
// Add elements to the answer
foreach (var p in m3) {
for (int i = 0; i < p.Value; i++) {
ans.Add(p.Key);
}
}
return ans;
}
public static void Main() {
int[] a = {3, 4, 2, 2, 4};
int[] b = {3, 2, 2, 7};
List<int> ans = commonElements(a, b);
Console.Write("[");
for (int i = 0; i < ans.Count; i++) {
Console.Write(ans[i]);
if (i != ans.Count - 1)
Console.Write(", ");
}
Console.WriteLine("]");
}
}
function commonElements(a, b) {
let ans = [];
// Maps to store element frequencies
let m1 = new Map();
let m2 = new Map();
let m3 = new Map();
// Count frequencies in first array
a.forEach(x => {
m1.set(x, (m1.get(x) || 0) + 1);
});
// Count frequencies in second array
b.forEach(x => {
m2.set(x, (m2.get(x) || 0) + 1);
});
// Store common elements with minimum frequency
for (let [key, value] of m1) {
if (m2.has(key)) {
m3.set(key, Math.min(value, m2.get(key)));
}
}
// Add elements to the answer in sorted order
let keys = [...m3.keys()].sort((a, b) => a - b);
for (let key of keys) {
for (let i = 0; i < m3.get(key); i++) {
ans.push(key);
}
}
return ans;
}
// Driver code
let a = [3, 4, 2, 2, 4];
let b = [3, 2, 2, 7];
let ans = commonElements(a, b);
console.log(`[${ans.join(', ')}]`);
Output
[2, 2, 3]