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++
// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find last remaining
// integer in the given array
int lastNumber(vector<int>& arr)
{
// Variable to store the
// frequency of 1
int one = 0;
// Loop to iterate the
// given array
for (int x : arr) {
if (x == 1) {
one += 1;
}
}
// If frequency of 1 is even
if (one % 2 == 0)
return 0;
// If frequency of 1 is odd
return 1;
}
// Driver Code
int main()
{
vector<int> arr = { 1, 0, 0, 0, 1 };
cout << lastNumber(arr);
}
Java
// Java program of the above approach
import java.util.ArrayList;
class GFG {
// Function to find last remaining
// integer in the given array
static Integer lastNumber(ArrayList<Integer> arr)
{
// Variable to store the
// frequency of 1
int one = 0;
// Loop to iterate the
// given array
for (int x : arr) {
if (x == 1) {
one += 1;
}
}
// If frequency of 1 is even
if (one % 2 == 0)
return 0;
// If frequency of 1 is odd
return 1;
}
// Driver Code
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));
}
}
// This code is contributed by gfgking
Python3
# python program of the above approach
# Function to find last remaining
# integer in the given array
def lastNumber(arr):
# Variable to store the
# frequency of 1
one = 0
# Loop to iterate the
# given array
for x in arr:
if (x == 1):
one += 1
# If frequency of 1 is even
if (one % 2 == 0):
return 0
# If frequency of 1 is odd
return 1
# Driver Code
if __name__ == "__main__":
arr = [1, 0, 0, 0, 1]
print(lastNumber(arr))
# This code is contributed by rakeshsahni
C#
// C# program of the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to find last remaining
// integer in the given array
static int lastNumber(List<int> arr)
{
// Variable to store the
// frequency of 1
int one = 0;
// Loop to iterate the
// given array
foreach(int x in arr)
{
if (x == 1)
{
one += 1;
}
}
// If frequency of 1 is even
if (one % 2 == 0)
return 0;
// If frequency of 1 is odd
return 1;
}
// Driver Code
public static void Main()
{
List<int> arr = new List<int>(){ 1, 0, 0, 0, 1 };
Console.WriteLine(lastNumber(arr));
}
}
// This code is contributed by ukasp
JavaScript
<script>
// JavaScript code for the above approach
// Function to find last remaining
// integer in the given array
function lastNumber(arr) {
// Variable to store the
// frequency of 1
let one = 0;
// Loop to iterate the
// given array
for (let x of arr) {
if (x == 1) {
one += 1;
}
}
// If frequency of 1 is even
if (one % 2 == 0)
return 0;
// If frequency of 1 is odd
return 1;
}
// Driver Code
let arr = [1, 0, 0, 0, 1];
document.write(lastNumber(arr));
// This code is contributed by Potta Lokesh
</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));
// Initialize diagonal elements
for (int i = 0; i < n; i++) {
dp[i][i] = arr[i];
}
// Calculate remaining element for each subarray
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]) {
// If both numbers are the same, set the remaining element to 0
dp[i][j] = 0;
} else {
// If both numbers are different, set the remaining element to 1
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];
// Initialize diagonal elements
for (int i = 0; i < n; i++) {
dp[i][i] = arr[i];
}
// Calculate remaining element for each subarray
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]) {
// If both numbers are the same, set the remaining element to 0
dp[i][j] = 0;
} else {
// If both numbers are different, set the remaining element to 1
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)]
# Initialize diagonal elements
for i in range(n):
dp[i][i] = arr[i]
# Calculate remaining element for each subarray
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
if arr[i] == arr[j]:
# If both numbers are the same, set the remaining element to 0
dp[i][j] = 0
else:
# If both numbers are different, set the remaining element to 1
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];
// Initialize diagonal elements
for (int i = 0; i < n; i++)
{
dp[i, i] = arr[i];
}
// Calculate remaining element for each subarray
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])
{
// If both numbers are the same, set the remaining element to 0
dp[i, j] = 0;
}
else
{
// If both numbers are different, set the remaining element to 1
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));
// Initialize diagonal elements
for (let i = 0; i < n; i++) {
dp[i][i] = arr[i];
}
// Calculate remaining element for each subarray
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]) {
// If both numbers are the same, set the remaining element to 0
dp[i][j] = 0;
} else {
// If both numbers are different, set the remaining element to 1
dp[i][j] = 1;
}
}
}
return dp[0][n - 1];
}
// Main function
const arr = [0, 0, 1];
const result = lastRemainingNumber(arr);
console.log(result); // Print the result to the console
Time Complexity: O(N^2)
Auxiliary Space: O(N^2)
Similar Reads
Make Palindrome binary string with exactly a 0s and b 1s by replacing wild card ?
Given a string S of N characters consisting of '?', '0', and '1' and two integers a and b, the task is to find a palindromic binary string with exactly a 0s and b 1s by replacing the '?' with either '0' or '1'. Examples: Input: S = "10?????1", a = 4, b = 4Output: 10100101Explanation: The output stri
12 min read
Count Substrings that can be made of length 1 by replacing "01" or "10" with 1 or 0
Given a binary string S of length N, the task is to find the number of pairs of integers [L, R] 1 ⤠L < R ⤠N such that S[L . . . R] (the substring of S from L to R) can be reduced to 1 length string by replacing substrings "01" or "10" with "1" and "0" respectively. Examples: Input: S = "0110"Ou
4 min read
Reduce the Array to 0 by decreasing elements by 1 or replacing at most K elements by 0
Given an array arr[] of N integers and a positive integer K, the task is to find the minimum number of operations required to reduce all array elements to 0 such that in each operation reduce any array element by 1 and independently at most K array element can be reduced to 0. Examples: Input: arr[]
6 min read
Replace '?' to convert given string to a binary string with maximum count of '0' and "10"
Given string str, consisting of three different types of characters '0', '1' and '?', the task is to convert the given string to a binary string by replacing the '?' characters with either '0' or '1' such that the count of 0s and 10 in the binary string is maximum. Examples: Input: str = 10?0?11Outp
4 min read
Count of possible distinct Binary strings after replacing "11" with "0"
Given a binary string str of size N containing 0 and 1 only, the task is to count all possible distinct binary strings when a substring "11" can be replaced by "0". Examples: Input: str = "11011"Output: 4Explanation: All possible combinations are "11011", "0011", "1100", "000". Input: str = "1100111
15 min read
Reduce a given Binary Array to a single element by removal of Triplets
Given an binary array arr[] of size N, the task is to reduce the array to a single element by the following two operations: A triplet of consecutive 0's or 1's remains unchanged.A triplet of consecutive array elements consisting of two 0's and a single 1 or vice versa can be converted to more freque
5 min read
Minimum operations required to convert a binary string to all 0s or all 1s
Given a binary string str, the task is to find the minimum number of operations required to make all the characters of the string same i.e. either the resultant string contains all 0s or all 1s. In a single operation, any block of consecutive 0s can be converted to a block of consecutive 1s of the s
4 min read
Find Index of 0 to be replaced with 1 to get longest continuous sequence of 1s in a binary array | Set-2
Given an array of 0s and 1s, find the position of 0 to be replaced with 1 to get longest continuous sequence of 1s. Expected time complexity is O(n) and auxiliary space is O(1). Examples: Input : arr[] = {1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1}Output : Index 9Assuming array index starts from 0, repla
15+ min read
Count ways to replace '?' in a Binary String to make the count of 0s and 1s same as that of another string
Given two binary strings S1 and S2 of size N and M respectively such that the string S2 also contains the character '?', the task is to find the number of ways to replace '?' in the string S2 such that the count of 0s and 1s in the string S2 is the same as in the string S1. Examples: Input: S1 = "10
11 min read
Check if it is possible to rearrange a binary string with alternate 0s and 1s
Given a binary string of length, at least two. We need to check if it is possible to rearrange a binary string such that there are alternate 0s and 1s. If possible, then the output is YES, otherwise the output is NO. Examples: Input : 1011 Output : NO We can't rearrange the string such that it has a
5 min read