Construct Binary Array having same number of unequal elements with two other Arrays
Last Updated :
29 Mar, 2023
Given two binary arrays A[] and B[] of size N, the task is to construct the lexicographically smallest binary array X[] such that the number of non-equal elements in A and X is equal to the number of non-equal elements in B and X. If such an array does not exist return -1.
Note: If there are multiple possible answers, print any of them
Examples:
Input: N = 5, A = {0, 0, 1, 0, 0}, B = {1, 0, 0, 1, 1}
Output: {0, 0, 0, 0, 1}
Explanation: Consider arrays X = {0, 0, 0, 0, 1}. It can be seen 3rd and 5th elements of A[] and X[] are not equal. So, there are 2 unequal elements in A and X. Similarly, it can be seen that 1st and 4th elements of X[] and B[] are unequal. Again, the number of unequal elements is 2, which is same as the number of unequal elements in A[] and X[]. Hence, X = {0, 0, 0, 0, 1} is the required array.
Input: N = 1, A = {0}, B = {1}
Output: -1
Approach: To solve the problem follow the below observations:
Let f(X, Y) denote the number of unequal elements in two arrays X and Y. Let D = f(X, A) - f(X, B). Here, we want to find the lexicographically smallest array X such that D = 0.
Here, we can observe that :
- For i such that A[i] = B[i], whether X[i] is 0 or 1 does not impact the D.
- For i such that A[i] ? B[i], X[i] = A[i] adds 1 to the D and X[i] = B[i] adds (-1) to the D.
Thus, to get D = 0, among the indices where A[i] != B[i], the indices where X[i] = A[i] must be equal to the indices having
X[i] = B[i]. It can be concluded from the above observation that it is impossible to make D = 0 (and hence to construct the array X), if the indices such that A[i] != B[i] are odd in number.
To make sure the array is lexicographically smallest:
- As we have already seen, the indices such that A[i] = B[i] do not contribute to D, hence we would make X[i] = 0 for such indices.
- For indices with A[i] ? B[i], following greedy approach is used to ensure the lexicographically smallest resultant array:
- Iterate through such indices. Prioritize assigning 0 to X[i] as long as it is possible [i.e., difference with any one of A[i] or B[i] reaches D/2] and then fill the other indices with 1.
Follow the steps mentioned below to implement the idea:
- Iterate the arrays from i = 0 to N-1:
- Find the value of D (i.e. the number of indices where A[i] and B[i] are different).
- If D is odd return -1.
- Otherwise, do the following:
- Create an array to store X[].
- Now iterate from i = 0 to N-1:
- If A[i] and B[i] are same push 0 in X[].
- Otherwise, push 0 if difference with any of A[] or B[] has not reached the value of D/2.
- Else, push the value of A[i] or B[i] depending on the difference with which has not yet become D/2.
- Return X[] as the required answer.
Below is the implementation of the above approach.
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Function to print lexicographically
// smallest binary array X[] such that
// number of non-equal elements in A and X
// is equal to the number of non-equal
// elements in B and X.
vector<int> printArray(int N, int A[], int B[])
{
// Variable to store count of unequal
// integers in A and B
int count = 0;
// Vector to store answer
vector<int> ans;
// Counting unequal elements
for (int i = 0; i < N; i++) {
if (A[i] != B[i]) {
count++;
}
}
// If unequal elements are odd,
// return -1
if (count % 2 != 0) {
ans.push_back(-1);
return ans;
}
int countA = 0;
int countB = 0;
// Greedily constructing array X[]
for (int i = 0; i < N; i++) {
// If A[i] != B[i], fill the current
// index of X[] greedily with
// either 1 or 0
if (A[i] != B[i]) {
if (A[i] == 0) {
countA++;
if (countA <= count / 2) {
ans.push_back(0);
}
else {
ans.push_back(1);
}
}
if (B[i] == 0) {
countB++;
if (countB <= count / 2) {
ans.push_back(0);
}
else {
ans.push_back(1);
}
}
}
// Else simply fill 0 into the index
else {
ans.push_back(0);
}
}
// Return the resultant array
return ans;
}
// Driver code
int main()
{
int A[] = { 0, 0, 1, 0, 0 };
int B[] = { 1, 0, 0, 1, 1 };
int N = sizeof(A) / sizeof(A[0]);
// Function Call
vector<int> res = printArray(N, A, B);
for (int x : res)
cout << x << " ";
return 0;
}
Java
// Java code to implement the approach
import java.io.*;
import java.util.*;
class GFG
{
// Function to print lexicographically
// smallest binary array X[] such that
// number of non-equal elements in A and X
// is equal to the number of non-equal
// elements in B and X.
public static ArrayList<Integer>
printArray(int N, int A[], int B[])
{
// Variable to store count of unequal
// integers in A and B
int count = 0;
// Vector to store answer
ArrayList<Integer> ans = new ArrayList<Integer>();
// Counting unequal elements
for (int i = 0; i < N; i++) {
if (A[i] != B[i]) {
count++;
}
}
// If unequal elements are odd,
// return -1
if (count % 2 != 0) {
ans.add(-1);
return ans;
}
int countA = 0;
int countB = 0;
// Greedily constructing array X[]
for (int i = 0; i < N; i++) {
// If A[i] != B[i], fill the current
// index of X[] greedily with
// either 1 or 0
if (A[i] != B[i]) {
if (A[i] == 0) {
countA++;
if (countA <= count / 2) {
ans.add(0);
}
else {
ans.add(1);
}
}
if (B[i] == 0) {
countB++;
if (countB <= count / 2) {
ans.add(0);
}
else {
ans.add(1);
}
}
}
// Else simply fill 0 into the index
else {
ans.add(0);
}
}
// Return the resultant array
return ans;
}
// Driver Code
public static void main(String[] args)
{
int A[] = { 0, 0, 1, 0, 0 };
int B[] = { 1, 0, 0, 1, 1 };
int N = A.length;
// Function Call
ArrayList<Integer> res = printArray(N, A, B);
for (Integer x : res)
System.out.print(x + " ");
}
}
// This code is contributed by Rohit Pradhan
Python3
# Python code to implement the approach
# Function to print lexicographically
# smallest binary array X[] such that
# number of non-equal elements in A and X
# is equal to the number of non-equal
# elements in B and X.
def printArray(N, A, B):
# Variable to store count of unequal
# integers in A and B
count = 0
# Vector to store answer
ans = [0]*N
# = Counting unequal elements
for i in range(0, N):
if (A[i] != B[i]):
count += 1
# If unequal elements are odd,
# return -1
if (count % 2 != 0):
ans[i]= -1
return ans
countA = 0
countB = 0
# Greedily constructing array X[]
for i in range(0, N):
# If A[i] != B[i], fill the current
# index of X[] greedily with
# either 1 or 0
if (A[i] != B[i]):
if (A[i] == 0):
countA += 1
if (countA <= count / 2):
ans[i] = 0
else:
ans[i] = 1
if (B[i] == 0):
countB += 1
if (countB <= count / 2):
ans[i] = 0
else:
ans[i] = 1
# Else simply fill 0 into the index
else:
ans[i] = 0
# Return the resultant array
return ans
# Driver code
A = [0, 0, 1, 0, 0]
B = [1, 0, 0, 1, 1]
N = len(A)
# Function Call
res = printArray(N, A, B)
for x in range(0, len(res)):
print(res[x])
# This code is contributed by ksam24000
C#
// C# code to implement the approach
using System;
using System.Collections.Generic;
public class GFG {
// Function to print lexicographically
// smallest binary array X[] such that
// number of non-equal elements in A and X
// is equal to the number of non-equal
// elements in B and X.
static int[] printArray(int N, int[] A, int[] B)
{
// Variable to store count of unequal
// integers in A and B
int count = 0;
// Vector to store answer
int[] ans = new int[N];
int k = 0;
// Counting unequal elements
for (int i = 0; i < N; i++) {
if (A[i] != B[i]) {
count++;
}
}
// If unequal elements are odd,
// return -1
if (count % 2 != 0) {
ans[k++] = -1;
return ans;
}
int countA = 0;
int countB = 0;
// Greedily constructing array X[]
for (int i = 0; i < N; i++) {
// If A[i] != B[i], fill the current
// index of X[] greedily with
// either 1 or 0
if (A[i] != B[i]) {
if (A[i] == 0) {
countA++;
if (countA <= count / 2) {
ans[k++] = 0;
}
else {
ans[k++] = 1;
}
}
if (B[i] == 0) {
countB++;
if (countB <= count / 2) {
ans[k++] = 0;
}
else {
ans[k++] = 1;
}
}
}
// Else simply fill 0 into the index
else {
ans[k++] = 0;
}
}
// Return the resultant array
return ans;
}
// Driver code
public static void Main(string[] args)
{
int[] A = { 0, 0, 1, 0, 0 };
int[] B = { 1, 0, 0, 1, 1 };
int N = 5;
// Function Call
int[] res = printArray(N, A, B);
for (int i = 0; i < res.Length; i++)
Console.Write(res[i] + " ");
return;
}
}
// This code is contributed by garg28harsh.
JavaScript
// JavaScript code to implement the approach
// Function to print lexicographically
// smallest binary array X[] such that
// number of non-equal elements in A and X
// is equal to the number of non-equal
// elements in B and X.
const printArray = (N, A, B) => {
// Variable to store count of unequal
// integers in A and B
let count = 0;
// Vector to store answer
let ans = [];
// Counting unequal elements
for (let i = 0; i < N; i++) {
if (A[i] != B[i]) {
count++;
}
}
// If unequal elements are odd,
// return -1
if (count % 2 != 0) {
ans.push(-1);
return ans;
}
let countA = 0;
let countB = 0;
// Greedily constructing array X[]
for (let i = 0; i < N; i++) {
// If A[i] != B[i], fill the current
// index of X[] greedily with
// either 1 or 0
if (A[i] != B[i]) {
if (A[i] == 0) {
countA++;
if (countA <= parseInt(count / 2)) {
ans.push(0);
}
else {
ans.push(1);
}
}
if (B[i] == 0) {
countB++;
if (countB <= parseInt(count / 2)) {
ans.push(0);
}
else {
ans.push(1);
}
}
}
// Else simply fill 0 into the index
else {
ans.push(0);
}
}
// Return the resultant array
return ans;
}
// Driver code
let A = [0, 0, 1, 0, 0];
let B = [1, 0, 0, 1, 1];
let N = A.length;
// Function Call
let res = printArray(N, A, B);
for (let x in res)
console.log(`${res[x]} `);
// This code is contributed by rakeshsahni
PHP
<?php
// Function to print lexicographically
// smallest binary array X[] such that
// number of non-equal elements in A and X
// is equal to the number of non-equal
// elements in B and X.
function printArray($N, $A, $B) {
// Variable to store count of unequal
// integers in A and B
$count = 0;
// Vector to store answer
$ans = array();
// Counting unequal elements
for ($i = 0; $i < $N; $i++) {
if ($A[$i] != $B[$i])
$count++;
}
// If unequal elements are odd,
// return -1
if ($count % 2 != 0) {
array_push($ans, -1);
return $ans;
}
$countA = 0;
$countB = 0;
// Greedily constructing array X[]
for ($i = 0; $i < $N; $i++) {
// If A[i] != B[i], fill the current
// index of X[] greedily with
// either 1 or 0
if ($A[$i] != $B[$i]) {
if ($A[$i] == 0) {
$countA++;
if ($countA <= $count / 2)
array_push($ans, 0);
else
array_push($ans, 1);
}
if ($B[$i] == 0) {
$countB++;
if ($countB <= $count / 2)
array_push($ans, 0);
else
array_push($ans, 1);
}
}
// Else simply fill 0 into the index
else {
array_push($ans, 0);
}
}
// Return the resultant array
return $ans;
}
// Driver code
$A = array(0, 0, 1, 0, 0);
$B = array(1, 0, 0, 1, 1);
$N = count($A);
// Function Call
$res = printArray($N, $A, $B);
for ($x = 0; $x < count($res); $x++)
echo $res[$x] . " ";
// This code is contributed by Kanishka Gupta
?>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
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
Partition an array into two subsets with equal count of unique elements Given an array arr[] consisting of N integers, the task is to partition the array into two subsets such that the count of unique elements in both the subsets is the same and for each element, print 1 if that element belongs to the first subset. Otherwise, print 2. If it is not possible to do such a
13 min read
Check if two unsorted arrays (with duplicates allowed) have same elements Given two unsorted arrays, check whether both arrays have the same set of elements or not. Examples: Input : A = {2, 5, 6, 8, 10, 2, 2} B = {2, 5, 5, 6, 8, 5, 6} Output : No Input : A = {2, 5, 6, 8, 2, 10, 2} B = {2, 5, 6, 8, 2, 10, 2} Output : Yes Input : A = {2, 5, 8, 6, 10, 2, 2} B = {2, 5, 6, 8,
13 min read
Construct an Array having K Subarrays with all distinct elements Given integers N and K, the task is to construct an array arr[] of size N using numbers in the range [1, N] such that it has K sub-arrays whose all the elements are distinct. Note: If there are multiple possible answers return any of them. Examples: Input: N = 5, K = 8Output: {1, 2, 3, 3, 3}Explanat
7 min read
Construct Array of given size with elements at even positions divisible by their adjacent left Given an integer N, the task is to construct and print an Array, such that: The size of array is NThe elements in array are in range [1, 2*N]Each element in the array are distinctThe elements at even positions are divisible by their adjacent left, but this must not be true for odd position elements,
11 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
Count elements of same value placed at same indices of two given arrays Given two arrays A[] and B[] of N unique elements, the task is to find the maximum number of matched elements from the two given arrays. Elements of the two arrays are matched if they are of the same value and can be placed at the same index (0-based indexing).(By right shift or left shift of the tw
8 min read
Intersection of Two Sorted Arrays with Distinct Elements Given two sorted arrays a[] and b[] with distinct elements of size n and m respectively, the task is to find intersection (or common elements) of the two arrays. We need to return the intersection in sorted order.Note: Intersection of two arrays can be defined as a set containing distinct common ele
13 min read
Making elements of two arrays same with minimum increment/decrement Given two arrays of same size, we need to convert the first array into another with minimum operations. In an operation, we can either increment or decrement an element by one. Note that orders of appearance of elements do not need to be same. Here to convert one number into another we can add or su
6 min read
Count subarrays having total distinct elements same as original array Given an array of n integers. Count the total number of sub-arrays having total distinct elements, the same as that of the total distinct elements of the original array. Examples: Input : arr[] = {2, 1, 3, 2, 3} Output : 5 Total distinct elements in array is 3 Total sub-arrays that satisfy the condi
11 min read