Make given Binary array of size two to all 0s in a single line
Last Updated :
14 Jul, 2022
Given a binary array arr[N], (where N = 2) of size two having at least one element as zero. The task is to write a single line function to set both elements of the array to zero. There is a constraint to writing the function. The ternary operator and direct assignment of elements cannot be used.
As per problem constraints, only three combinations of array elements are possible:
- arr[0] = 1 and arr[1] = 0
- arr[0] = 0 and arr[1] = 1
- arr[0] = 0 and arr[1] = 0
This article discusses the following methods:
- Using only assignment operator.
- Using assignment operator two times.
- negation (!) operator (logical NOT).
Let's start discussing each of these methods in detail.
1. Using only assignment operator:
The assignment operator can be used to set both the elements of the given binary array to 0, but in this approach, the indexes are not used directly.
Approach:
There are three ways to achieve this:
1. arr[arr[1]] = arr[arr[0]]
If arr={0, 1}, then arr[0] will be assigned to arr[1].
If arr={1, 0}, then arr[1] will be assigned to arr[0].
2. arr[arr[1]] = 0
If arr[1]=0, then arr[0] will be 1, so arr[arr[1]] will make arr[0]=0.
If arr[1]=1, then arr[1] will be 1, so arr[arr[1]] will make arr[1]=0.
3. arr[1 – arr[0]] = arr[1 – arr[1]]
If arr[1]=0 and arr[0]=1, then 1-arr[1] will be 1, so arr[1] will be assigned to arr[0].
If arr[1]=1 and arr[0]=0, then 1-arr[1] will be 0, so arr[0] will be assigned to arr[1].
Below is the C++ code to implement the approach:
C++
// C++ program to set both elements
// to 0 in binary array[2].
#include <iostream>
using namespace std;
void MakeBothZeros(int arr[])
{
arr[arr[1]] = arr[arr[0]];
// Two other approaches to solve
// the problem
// arr[arr[1]] = 0;
// arr[1 - arr[0]] = arr[1 - arr[1]];
}
// Driver code
int main()
{
int First_Arr[] = {0, 1};
MakeBothZeros(First_Arr);
cout << First_Arr[0] << " " <<
First_Arr[1] << endl;
int Second_Arr[] = {1, 0};
MakeBothZeros(Second_Arr);
cout << Second_Arr[0] << " " <<
Second_Arr[1] << endl;
int Thrd_Arr[] = {0, 0};
MakeBothZeros(Thrd_Arr);
cout << Thrd_Arr[0] << " " <<
Thrd_Arr[1] << endl;
return 0;
}
Java
// Java program to set both elements
// to 0 in binary array[2]
import java.util.*;
class GFG{
static void MakeBothZeros(int arr[])
{
arr[arr[1]] = arr[arr[0]];
// Two other approaches to solve
// the problem
// arr[arr[1]] = 0;
// arr[1 - arr[0]] = arr[1 - arr[1]];
}
// Driver code
public static void main(String[] args)
{
int First_Arr[] = {0, 1};
MakeBothZeros(First_Arr);
System.out.print(First_Arr[0]+ " " +
First_Arr[1] +"\n");
int Second_Arr[] = {1, 0};
MakeBothZeros(Second_Arr);
System.out.print(Second_Arr[0]+ " " +
Second_Arr[1] +"\n");
int Thrd_Arr[] = {0, 0};
MakeBothZeros(Thrd_Arr);
System.out.print(Thrd_Arr[0]+ " " +
Thrd_Arr[1] +"\n");
}
}
// This code is contributed by 29AjayKumar
Python3
# Python code for the above approach
def MakeBothZeros(arr):
arr[arr[1]] = arr[arr[0]]
# Two other approaches to solve
# the problem
# arr[arr[1]] = 0;
# arr[1 - arr[0]] = arr[1 - arr[1]];
# Driver code
First_Arr = [0, 1]
MakeBothZeros(First_Arr)
print(f"{First_Arr[0]} {First_Arr[1]} ")
Second_Arr = [1, 0]
MakeBothZeros(Second_Arr)
print(f"{Second_Arr[0]} {Second_Arr[1]} ")
Thrd_Arr = [0, 0]
MakeBothZeros(Thrd_Arr)
print(f"{Thrd_Arr[0]} {Thrd_Arr[1]} ")
# This code is contributed by GFGKING
C#
// C# program to set both elements
// to 0 in binary array[2]
using System;
class GFG {
static void MakeBothZeros(int[] arr)
{
arr[arr[1]] = arr[arr[0]];
// Two other approaches to solve
// the problem
// arr[arr[1]] = 0;
// arr[1 - arr[0]] = arr[1 - arr[1]];
}
// Driver code
public static void Main()
{
int[] First_Arr = { 0, 1 };
MakeBothZeros(First_Arr);
Console.WriteLine(First_Arr[0] + " "
+ First_Arr[1]);
int[] Second_Arr = { 1, 0 };
MakeBothZeros(Second_Arr);
Console.WriteLine(Second_Arr[0] + " "
+ Second_Arr[1]);
int[] Thrd_Arr = { 0, 0 };
MakeBothZeros(Thrd_Arr);
Console.WriteLine(Thrd_Arr[0] + " " + Thrd_Arr[1]);
}
}
// This code is contributed by ukasp.
JavaScript
<script>
// JavaScript code for the above approach
function MakeBothZeros(arr) {
arr[arr[1]] = arr[arr[0]];
// Two other approaches to solve
// the problem
// arr[arr[1]] = 0;
// arr[1 - arr[0]] = arr[1 - arr[1]];
}
// Driver code
let First_Arr = [0, 1];
MakeBothZeros(First_Arr);
document.write(First_Arr[0] + " " +
First_Arr[1] + "<br>");
let Second_Arr = [1, 0];
MakeBothZeros(Second_Arr);
document.write(Second_Arr[0] + " " +
Second_Arr[1] + '<br>');
let Thrd_Arr = [0, 0];
MakeBothZeros(Thrd_Arr);
document.write(Thrd_Arr[0] + " " +
Thrd_Arr[1] + '<br>');
// This code is contributed by Potta Lokesh
</script>
Time Complexity: O(1), the code will run in a constant time.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
2. Using assignment operator two times:
As listed under the constraints, direct assignment is not allowed. Thus arr[0]=0 and arr[1]=0 are not valid statements. The assignment operator will be used twice to set both elements to zero.
Approach:
There are three ways to achieve this:
1. arr[0] = arr[1] = arr[0] & arr[1]
if any one of the elements is 1.
AND of 1 and 0 is always 0. So, both gets value 0.
2. arr[0] = arr[1] -= arr[1]
If arr[1]=1 then arr[1] gets 1-1=0 so, both becomes 0.
3. arr[1] = arr[0] -= arr[0]
If arr[0]=1, then arr[0] gets 1-1=0.
else arr[0]= 0-0 = 0. So, both becomes 0.
Below is the C++ program to implement the approach:
C++
// C++ program to set both elements
// to 0 in binary array[2].
#include <iostream>
using namespace std;
void MakeBothZeros(int arr[])
{
arr[0] = arr[1] = arr[0] & arr[1];
// Two other approaches to solve
// the problem
// arr[0] = arr[1] -= arr[1];
// arr[1] = arr[0] -= arr[0];
}
// Driver code
int main()
{
int First_Arr[] = {0, 1};
MakeBothZeros(First_Arr);
cout << First_Arr[0] << " " <<
First_Arr[1] << endl;
int Second_Arr[] = {1, 0};
MakeBothZeros(Second_Arr);
cout << Second_Arr[0] << " " <<
Second_Arr[1] << endl;
int Thrd_Arr[] = {0, 0};
MakeBothZeros(Thrd_Arr);
cout << Thrd_Arr[0] << " " <<
Thrd_Arr[1] << endl;
return 0;
}
Java
// Java program to set both elements
// to 0 in binary array[2].
import java.util.*;
class GFG{
static void MakeBothZeros(int arr[])
{
arr[0] = arr[1] = arr[0] & arr[1];
// Two other approaches to solve
// the problem
// arr[0] = arr[1] -= arr[1];
// arr[1] = arr[0] -= arr[0];
}
// Driver code
public static void main(String[] args)
{
int First_Arr[] = {0, 1};
MakeBothZeros(First_Arr);
System.out.print(First_Arr[0]+ " " +
First_Arr[1] +"\n");
int Second_Arr[] = {1, 0};
MakeBothZeros(Second_Arr);
System.out.print(Second_Arr[0]+ " " +
Second_Arr[1] +"\n");
int Thrd_Arr[] = {0, 0};
MakeBothZeros(Thrd_Arr);
System.out.print(Thrd_Arr[0]+ " " +
Thrd_Arr[1] +"\n");
}
}
// This code is contributed by 29AjayKumar
Python3
# Python program to set both elements
# to 0 in binary array[2].
def MakeBothZeros(arr):
arr[0] = arr[1] = arr[0] & arr[1]
# Two other approaches to solve
# the problem
# arr[0] = arr[1] -= arr[1];
# arr[1] = arr[0] -= arr[0];
# Driver code
First_Arr = [0, 1]
MakeBothZeros(First_Arr)
print(First_Arr[0], end=" ")
print(First_Arr[1])
Second_Arr = [0, 1]
MakeBothZeros(Second_Arr)
print(Second_Arr[0], end=" ")
print(Second_Arr[1])
Thrd_Arr = [0, 0]
MakeBothZeros(Thrd_Arr)
print(Thrd_Arr[0], end=" ")
print(Thrd_Arr[1])
# This code is contributed by Samim Hossain Mondal.
C#
// C# program to set both elements
// to 0 in binary array[2].
using System;
public class GFG
{
static void MakeBothZeros(int []arr)
{
arr[0] = arr[1] = arr[0] & arr[1];
// Two other approaches to solve
// the problem
// arr[0] = arr[1] -= arr[1];
// arr[1] = arr[0] -= arr[0];
}
// Driver code
public static void Main(String[] args) {
int[] First_Arr = { 0, 1 };
MakeBothZeros(First_Arr);
Console.Write(First_Arr[0] + " " + First_Arr[1] + "\n");
int []Second_Arr = { 1, 0 };
MakeBothZeros(Second_Arr);
Console.Write(Second_Arr[0] + " " + Second_Arr[1] + "\n");
int []Thrd_Arr = { 0, 0 };
MakeBothZeros(Thrd_Arr);
Console.Write(Thrd_Arr[0] + " " + Thrd_Arr[1] + "\n");
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// Javascript program to set both elements
// to 0 in binary array[2].
function MakeBothZeros(arr) {
arr[0] = arr[1] = arr[0] & arr[1]
// Two other approaches to solve
// the problem
// arr[0] = arr[1] -= arr[1];
// arr[1] = arr[0] -= arr[0];
}
// Driver code
let First_Arr = [0, 1];
MakeBothZeros(First_Arr);
document.write(First_Arr[0] + " " +
First_Arr[1]);
let Second_Arr = [1, 0];
MakeBothZeros(Second_Arr);
document.write(Second_Arr[0] + " " +
Second_Arr[1]);
let Thrd_Arr = [0, 0];
MakeBothZeros(Thrd_Arr);
document.write(Thrd_Arr[0] + " " +
Thrd_Arr[1]);
// This code is contributed by Samim Hossain Mondal.
</script>
Time Complexity: O(1), the code will run in a constant time.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Note:
Time complexity is O(1) since just one statement is used.
3. By using the negation (!) operator (logical NOT):
In this approach, the assignment operator is used with a negation operator to make both elements of the given array 0 in a single line of code.
Approach:
There are three ways to do this:
1. arr[!arr[0]] = arr[arr[0]]
If arr={0, 1} then index 1 is assigned the index 0 value.
If arr={1, 0} then index 0 is given the index 1 value.
2. arr[arr[1]] = arr[!arr[1]]
If arr={0, 1} then index 0 value is assigned to the index 1.
If arr={1, 0} then index 1 value is assigned to the index 0.
3. arr[!arr[0]] = arr[!arr[1]]
If arr={0, 1}, since 1 is the value at index 1, the index 0 value which is 0 again,
will be assigned to index 1, making array full of zeros.
If arr={1, 0} then index 1 value is assigned to the index 0.
Below is the C++ program to implement the approach:
C++
// C++ program to set both elements
// to 0 in binary array[2].
#include <iostream>
using namespace std;
void MakeBothZeros(int arr[])
{
arr[!arr[0]] = arr[arr[0]];
// Two other approaches to solve
// the problem
// arr[arr[1]] = arr[!arr[1]]
// arr[!arr[0]] = arr[!arr[1]]
}
// Driver code
int main()
{
int First_Arr[] = {0, 1};
MakeBothZeros(First_Arr);
cout << First_Arr[0] << " " <<
First_Arr[1] << endl;
int Second_Arr[] = {1, 0};
MakeBothZeros(Second_Arr);
cout << Second_Arr[0] << " " <<
Second_Arr[1] << endl;
int Thrd_Arr[] = {0, 0};
MakeBothZeros(Thrd_Arr);
cout << Thrd_Arr[0] << " " <<
Thrd_Arr[1] << endl;
return 0;
}
Java
// Java program to set both elements
// to 0 in binary array[2].
import java.util.*;
class GFG{
static void MakeBothZeros(int arr[])
{
int index = arr[0] == 0?1:0;
arr[index] = arr[arr[0]];
// Two other approaches to solve
// the problem
// arr[arr[1]] = arr[!arr[1]]
// arr[!arr[0]] = arr[!arr[1]]
}
// Driver code
public static void main(String[] args)
{
int First_Arr[] = {0, 1};
MakeBothZeros(First_Arr);
System.out.print(First_Arr[0]+ " " +
First_Arr[1] +"\n");
int Second_Arr[] = {1, 0};
MakeBothZeros(Second_Arr);
System.out.print(Second_Arr[0]+ " " +
Second_Arr[1] +"\n");
int Thrd_Arr[] = {0, 0};
MakeBothZeros(Thrd_Arr);
System.out.print(Thrd_Arr[0]+ " " +
Thrd_Arr[1] +"\n");
}
}
// This code is contributed by shikhasingrajput
Python3
# Python program to set both elements to 0 in binary array[2].
def MakeBothZeros(arr):
if (arr[0] == 0):
index = 1
else:
index = 0
arr[index] = arr[arr[0]]
First_Arr = [0, 1]
MakeBothZeros(First_Arr)
print(First_Arr[0], end=" ")
print(First_Arr[1])
Second_Arr = [0, 1]
MakeBothZeros(Second_Arr)
print(Second_Arr[0], end=" ")
print(Second_Arr[1])
Thrd_Arr = [0, 0]
MakeBothZeros(Thrd_Arr)
print(Thrd_Arr[0], end=" ")
print(Thrd_Arr[1])
# This code is contributed by lokesh (lokeshmvs21).
C#
// C# program to set both elements
// to 0 in binary array[2].
using System;
public class GFG{
static void MakeBothZeros(int []arr)
{
int index = arr[0] == 0?1:0;
arr[index] = arr[arr[0]];
// Two other approaches to solve
// the problem
// arr[arr[1]] = arr[!arr[1]]
// arr[!arr[0]] = arr[!arr[1]]
}
// Driver code
public static void Main(String[] args)
{
int []First_Arr = {0, 1};
MakeBothZeros(First_Arr);
Console.Write(First_Arr[0]+ " " +
First_Arr[1] +"\n");
int []Second_Arr = {1, 0};
MakeBothZeros(Second_Arr);
Console.Write(Second_Arr[0]+ " " +
Second_Arr[1] +"\n");
int []Thrd_Arr = {0, 0};
MakeBothZeros(Thrd_Arr);
Console.Write(Thrd_Arr[0]+ " " +
Thrd_Arr[1] +"\n");
}
}
// This code is contributed by shikhasingrajput
JavaScript
<script>
// JavaScript program to set both elements
// to 0 in binary array[2].
function MakeBothZeros(arr)
{
arr[Number(!arr[0])] = arr[arr[0]];
// Two other approaches to solve
// the problem
// arr[arr[1]] = arr[!arr[1]]
// arr[!arr[0]] = arr[!arr[1]]
}
// Driver code
let First_Arr = [0, 1];
MakeBothZeros(First_Arr);
document.write(First_Arr[0] + " " + First_Arr[1],"</br>");
let Second_Arr = [1, 0];
MakeBothZeros(Second_Arr);
document.write(Second_Arr[0] + " " + Second_Arr[1],"</br>")
let Third_Arr = [0, 0];
MakeBothZeros(Third_Arr);
document.write(Third_Arr[0] + " " + Third_Arr[1],"</br>")
// This code is contributed by shinjanpatra
</script>
Time Complexity: O(1), the code will run in a constant time.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn 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
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA 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
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem