Minimum value among AND of elements of every subset of an array
Last Updated :
16 Nov, 2022
Given an array of integers, the task is to find the AND of all elements of each subset of the array and print the minimum AND value among all those.
Examples:
Input: arr[] = {1, 2, 3}
Output: 0
AND of all possible subsets
(1 & 2) = 0,
(1 & 3) = 1,
(2 & 3) = 2 and
(1 & 2 & 3) = 0.
Minimum among these is 0.
Input: arr[] = {7, 2}
Output: 2
Approach: The minimum AND value of any subset of the array will be the AND of all the elements of the array. So, the simplest way is to find AND of all elements of sub-array.
Below is the implementation of the above approach:
Implementation:
C++
#include<bits/stdc++.h>
using namespace std;
void minAND( int arr[], int n)
{
int s = arr[0];
for ( int i = 1; i < n; i++)
{
s = s & arr[i];
}
cout << (s) << endl;
}
int main()
{
int arr[] = {1, 2, 3};
int n = sizeof (arr)/ sizeof ( int );
minAND(arr, n);
}
|
Java
class GFG
{
static void minAND( int [] arr, int n)
{
int s = arr[ 0 ];
for ( int i = 1 ; i < n; i++)
{
s = s & arr[i];
}
System.out.println(s);
}
public static void main(String[] args)
{
int [] arr = { 1 , 2 , 3 };
int n = arr.length;
minAND(arr, n);
}
}
|
Python
def minAND(arr, n):
s = arr[ 0 ]
for i in range ( 1 , n):
s = s & arr[i]
print (s)
arr = [ 1 , 2 , 3 ]
n = len (arr)
minAND(arr, n)
|
C#
class GFG
{
static void minAND( int [] arr, int n)
{
int s = arr[0];
for ( int i = 1; i < n; i++)
{
s = s & arr[i];
}
System.Console.WriteLine(s);
}
static void Main()
{
int [] arr = {1, 2, 3};
int n = arr.Length;
minAND(arr, n);
}
}
|
PHP
<?php
function minAND( $arr , $n )
{
$s = $arr [0];
for ( $i = 1; $i < $n ; $i ++)
{
$s = $s & $arr [ $i ];
}
print ( $s . "\n" );
}
$arr = array (1, 2, 3);
$n = count ( $arr );
minAND( $arr , $n );
?>
|
Javascript
<script>
function minAND(arr, n) {
let s = arr[0];
for (let i = 1; i < n; i++) {
s = s & arr[i];
}
document.write((s) + "<br>" );
}
let arr = [1, 2, 3];
let n = arr.length;
minAND(arr, n);
</script>
|
Time Complexity: O(n), where n is the size of the given array.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...