Reduce Binary Array by replacing both 0s or both 1s pair with 0 and 10 or 01 pair with 1
Last Updated :
19 Oct, 2023
Given a binary array arr[] of size N, the task is to find the last number remaining in the array after performing a set of operations. In each operation, select any two numbers and perform the following:
- If both numbers are the same, remove them from the array and insert a 0.
- If both numbers are different, remove both of them and insert a 1.
Example:
Input: arr[]={0, 0, 1}
Output: 1
Explanation: There are two possible sequence of operations as follows:
- arr[] = {0, 0, 1}, delete (0, 1) and insert 0 => arr[] = {0, 0}, delete (0, 0) and insert 1=> arr[] = {1}.
- arr[] = {0, 0, 1}, delete (0, 0) and insert 0 => arr[] = {0, 1}, delete (0, 1) and insert 1=> arr[] = {1}.
Hence the remaining element is 1.
Input: arr[]={1, 0, 0, 0, 1}
Output: 0
Approach: The given problem can be solved based on the following observations:
- 2 same numbers are getting replaced by a 0.
- 2 different numbers are getting replaced by a 1.
Now, the creating a table for each outcome:
Upon careful observation of the above table, it can be noticed that the table represents the bitwise XOR operation. Hence, the remaining integer will be equal to the bitwise XOR of the given array elements which can be further simplified as if the frequency of 1 is even, the result is 0, otherwise, it’s 1.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int lastNumber(vector< int >& arr)
{
int one = 0;
for ( int x : arr) {
if (x == 1) {
one += 1;
}
}
if (one % 2 == 0)
return 0;
return 1;
}
int main()
{
vector< int > arr = { 1, 0, 0, 0, 1 };
cout << lastNumber(arr);
}
|
Java
import java.util.ArrayList;
class GFG {
static Integer lastNumber(ArrayList<Integer> arr)
{
int one = 0 ;
for ( int x : arr) {
if (x == 1 ) {
one += 1 ;
}
}
if (one % 2 == 0 )
return 0 ;
return 1 ;
}
public static void main(String args[]) {
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add( 1 );
arr.add( 0 );
arr.add( 0 );
arr.add( 0 );
arr.add( 1 );
System.out.println(lastNumber(arr));
}
}
|
Python3
def lastNumber(arr):
one = 0
for x in arr:
if (x = = 1 ):
one + = 1
if (one % 2 = = 0 ):
return 0
return 1
if __name__ = = "__main__" :
arr = [ 1 , 0 , 0 , 0 , 1 ]
print (lastNumber(arr))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int lastNumber(List< int > arr)
{
int one = 0;
foreach ( int x in arr)
{
if (x == 1)
{
one += 1;
}
}
if (one % 2 == 0)
return 0;
return 1;
}
public static void Main()
{
List< int > arr = new List< int >(){ 1, 0, 0, 0, 1 };
Console.WriteLine(lastNumber(arr));
}
}
|
Javascript
<script>
function lastNumber(arr) {
let one = 0;
for (let x of arr) {
if (x == 1) {
one += 1;
}
}
if (one % 2 == 0)
return 0;
return 1;
}
let arr = [1, 0, 0, 0, 1];
document.write(lastNumber(arr));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Dynamic Approach:
- Create a dynamic programming table dp of size N x N, where N is the size of the input array arr[]. Each element dp[i][j] represents the last number remaining in the subarray starting from index i to index j.
- Initialize the diagonal elements of the dp table to the corresponding elements of the input array arr[].
- Traverse the subarrays of arr[] in a bottom-up manner, starting from smaller subarrays and building up to the larger subarrays.
- For each subarray, calculate the value of dp[i][i+len-1] using the following rules:
* If arr[i] == arr[i+len-1], set dp[i][i+len-1] to 0.
* If arr[i] != arr[i+len-1], set dp[i][i+len-1] to 1.
5. After completing the traversal, the remaining element in the entire array is stored in dp[0][N-1], which represents the last number remaining after performing all the operations.
6. Return the value in dp[0][N-1] as the last remaining number.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <vector>
using namespace std;
int lastRemainingNumber(vector< int >& arr) {
int n = arr.size();
vector<vector< int >> dp(n, vector< int >(n, 0));
for ( int i = 0; i < n; i++) {
dp[i][i] = arr[i];
}
for ( int len = 2; len <= n; len++) {
for ( int i = 0; i <= n - len; i++) {
int j = i + len - 1;
if (arr[i] == arr[j]) {
dp[i][j] = 0;
} else {
dp[i][j] = 1;
}
}
}
return dp[0][n - 1];
}
int main() {
vector< int > arr = {0, 0, 1};
int result = lastRemainingNumber(arr);
cout<< result << endl;
return 0;
}
|
Java
import java.util.Arrays;
import java.util.Scanner;
public class GFG {
public static int lastRemainingNumber( int [] arr) {
int n = arr.length;
int [][] dp = new int [n][n];
for ( int i = 0 ; i < n; i++) {
dp[i][i] = arr[i];
}
for ( int len = 2 ; len <= n; len++) {
for ( int i = 0 ; i <= n - len; i++) {
int j = i + len - 1 ;
if (arr[i] == arr[j]) {
dp[i][j] = 0 ;
} else {
dp[i][j] = 1 ;
}
}
}
return dp[ 0 ][n - 1 ];
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int [] arr = { 0 , 0 , 1 };
int result = lastRemainingNumber(arr);
System.out.println(result);
}
}
|
Python3
def lastRemainingNumber(arr):
n = len (arr)
dp = [[ 0 ] * n for _ in range (n)]
for i in range (n):
dp[i][i] = arr[i]
for length in range ( 2 , n + 1 ):
for i in range (n - length + 1 ):
j = i + length - 1
if arr[i] = = arr[j]:
dp[i][j] = 0
else :
dp[i][j] = 1
return dp[ 0 ][n - 1 ]
if __name__ = = "__main__" :
arr = [ 0 , 0 , 1 ]
result = lastRemainingNumber(arr)
print (result)
|
C#
using System;
class Program
{
static int LastRemainingNumber( int [] arr)
{
int n = arr.Length;
int [,] dp = new int [n, n];
for ( int i = 0; i < n; i++)
{
dp[i, i] = arr[i];
}
for ( int len = 2; len <= n; len++)
{
for ( int i = 0; i <= n - len; i++)
{
int j = i + len - 1;
if (arr[i] == arr[j])
{
dp[i, j] = 0;
}
else
{
dp[i, j] = 1;
}
}
}
return dp[0, n - 1];
}
static void Main()
{
int [] arr = { 0, 0, 1 };
int result = LastRemainingNumber(arr);
Console.WriteLine(result);
}
}
|
Javascript
function lastRemainingNumber(arr) {
const n = arr.length;
const dp = new Array(n).fill( null ).map(() => new Array(n).fill(0));
for (let i = 0; i < n; i++) {
dp[i][i] = arr[i];
}
for (let len = 2; len <= n; len++) {
for (let i = 0; i <= n - len; i++) {
const j = i + len - 1;
if (arr[i] === arr[j]) {
dp[i][j] = 0;
} else {
dp[i][j] = 1;
}
}
}
return dp[0][n - 1];
}
const arr = [0, 0, 1];
const result = lastRemainingNumber(arr);
console.log(result);
|
Time Complexity: O(N^2)
Auxiliary Space: O(N^2)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...