Open In App

Remove one element to get minimum OR value

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of N elements, the task is to remove one element from the array such that the OR value of the array is minimized. Print the minimized value.

Examples:

Input: arr[] = {1, 2, 3} 
Output:
All possible ways of deleting one element and their 
corresponding OR values will be: 
a) Remove 1 -> (2 | 3) = 3 
b) Remove 2 -> (1 | 3) = 3 
c) Remove 3 -> (1 | 2) = 3 
Thus, the answer will be 3.

Input: arr[] = {2, 2, 2} 
Output: 2  

Naive approach: One way will be to remove each element one by one and then finding the OR of the remaining elements. The time complexity of this approach will be O(N2).

Efficient approach: To solve the problem efficiently, the value of (OR(arr[0…i-1]) | OR(arr[i+1…N-1])) has to be determined for any element arr[i]. To do so, the prefix and the suffix OR arrays can be calculated say pre[] and suf[] where pre[i] stores OR(arr[0…i]) and suff[i] stores OR(arr[i…N-1]). Then the OR value of the array after deleting the ith element can be calculated as (pre[i-1] | suff[i+1]) and the answer will be minimum of all the possible OR values.

Below is the implementation of the above approach: 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the minimized OR
// after removing an element from the array
int minOR(int* arr, int n)
{
    // Base case
    if (n == 1)
        return 0;
 
    // Prefix and suffix OR array
    int pre[n], suf[n];
    pre[0] = arr[0], suf[n - 1] = arr[n - 1];
 
    // Computing prefix/suffix OR arrays
    for (int i = 1; i < n; i++)
        pre[i] = (pre[i - 1] | arr[i]);
    for (int i = n - 2; i >= 0; i--)
        suf[i] = (suf[i + 1] | arr[i]);
 
    // To store the final answer
    int ans = min(pre[n - 2], suf[1]);
 
    // Finding the final answer
    for (int i = 1; i < n - 1; i++)
        ans = min(ans, (pre[i - 1] | suf[i + 1]));
 
    // Returning the final answer
    return ans;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 2, 3 };
    int n = sizeof(arr) / sizeof(int);
 
    cout << minOR(arr, n);
 
    return 0;
}


Java




// Java implementation of the approach
class GFG
{
 
// Function to return the minimized OR
// after removing an element from the array
static int minOR(int []arr, int n)
{
    // Base case
    if (n == 1)
        return 0;
 
    // Prefix and suffix OR array
    int []pre = new int[n];
    int []suf = new int[n];
    pre[0] = arr[0];
    suf[n - 1] = arr[n - 1];
 
    // Computing prefix/suffix OR arrays
    for (int i = 1; i < n; i++)
        pre[i] = (pre[i - 1] | arr[i]);
    for (int i = n - 2; i >= 0; i--)
        suf[i] = (suf[i + 1] | arr[i]);
 
    // To store the final answer
    int ans = Math.min(pre[n - 2], suf[1]);
 
    // Finding the final answer
    for (int i = 1; i < n - 1; i++)
        ans = Math.min(ans, (pre[i - 1] |
                             suf[i + 1]));
 
    // Returning the final answer
    return ans;
}
 
// Driver code
public static void main(String[] args)
{
    int arr[] = { 1, 2, 3 };
    int n = arr.length;
 
    System.out.print(minOR(arr, n));
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 implementation of the approach
 
# Function to return the minimized OR
# after removing an element from the array
def minOR(arr, n):
     
    # Base case
    if (n == 1):
        return 0
 
    # Prefix and suffix OR array
    pre = [0] * n
    suf = [0] * n
    pre[0] = arr[0]
    suf[n - 1] = arr[n - 1]
 
    # Computing prefix/suffix OR arrays
    for i in range(1, n):
        pre[i] = (pre[i - 1] | arr[i])
    for i in range(n - 2, -1, -1):
        suf[i] = (suf[i + 1] | arr[i])
 
    # To store the final answer
    ans = min(pre[n - 2], suf[1])
 
    # Finding the final answer
    for i in range(1, n - 1):
        ans = min(ans, (pre[i - 1] | suf[i + 1]))
 
    # Returning the final answer
    return ans
 
# Driver code
if __name__ == '__main__':
    arr = [1, 2, 3]
    n = len(arr)
 
    print(minOR(arr, n))
 
# This code is contributed by Mohit Kumar


C#




// C# implementation of the approach
using System;
 
class GFG
{
     
    // Function to return the minimized OR
    // after removing an element from the array
    static int minOR(int []arr, int n)
    {
        // Base case
        if (n == 1)
            return 0;
     
        // Prefix and suffix OR array
        int []pre = new int[n];
        int []suf = new int[n];
         
        pre[0] = arr[0];
        suf[n - 1] = arr[n - 1];
     
        // Computing prefix/suffix OR arrays
        for (int i = 1; i < n; i++)
            pre[i] = (pre[i - 1] | arr[i]);
             
        for (int i = n - 2; i >= 0; i--)
            suf[i] = (suf[i + 1] | arr[i]);
     
        // To store the final answer
        int ans = Math.Min(pre[n - 2], suf[1]);
     
        // Finding the final answer
        for (int i = 1; i < n - 1; i++)
            ans = Math.Min(ans, (pre[i - 1] |
                                 suf[i + 1]));
     
        // Returning the final answer
        return ans;
    }
     
    // Driver code
    static public void Main ()
    {
        int []arr = { 1, 2, 3 };
        int n = arr.Length;
     
        Console.WriteLine(minOR(arr, n));
    }
}
 
// This code is contributed by AnkitRai01


Javascript




<script>
 
// Javascript implementation of the approach
 
// Function to return the minimized OR
// after removing an element from the array
function minOR(arr, n)
{
    // Base case
    if (n == 1)
        return 0;
 
    // Prefix and suffix OR array
    var pre = Array(n), suf = Array(n);
    pre[0] = arr[0], suf[n - 1] = arr[n - 1];
 
    // Computing prefix/suffix OR arrays
    for (var i = 1; i < n; i++)
        pre[i] = (pre[i - 1] | arr[i]);
    for (var i = n - 2; i >= 0; i--)
        suf[i] = (suf[i + 1] | arr[i]);
 
    // To store the final answer
    var ans = Math.min(pre[n - 2], suf[1]);
 
    // Finding the final answer
    for (var i = 1; i < n - 1; i++)
        ans = Math.min(ans, (pre[i - 1] | suf[i + 1]));
 
    // Returning the final answer
    return ans;
}
 
// Driver code
var arr = [1, 2, 3];
var n = arr.length;
document.write( minOR(arr, n));
 
</script>


Output: 

3

 

Time Complexity: O(n)
Auxiliary Space: O(n)

Space Optimized Approach: 

Count frequency of set bit of each element in 32 size array and traverse the array from most significant bit and check if any bit has frequency one, if we found such element than remove that particular element. The left element will participate in our actual result.

Below is the implementation of the above approach: 

C++




// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
 
int minOR(int arr[], int n)
{
    // Helper array where helper[i] will store the number of
    // elements in the array having the i'th bit set
    int helper[32];
    memset(helper, 0, sizeof(helper));
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < 32; j++) {
            // checking if the i'th bit is set
            if ((arr[i] & (1 << j))) {
                helper[j]++;
            }
        }
    }
 
    // Traverse the helper array from most significant bit
    // to find out the first index i where helper[i] = 1.
    // this means that there is only one element. in the
    // array having i'th bit as set. Let's say this element
    // as current. Since we are traversing the array from
    // most significant bit removing current element will
    // minimize the bitwise OR of the entire array
    int first_index = -1;
 
    for (int i = 31; i >= 0; i--) {
        if (helper[i] == 1) {
            first_index = i;
            break;
        }
    }
 
    // If there is no such element for which helper[i] = 1,
    // it means that either helper[i] = 0 or helper[i] >= 2
    // for i'th index. if helper[i] >=2 this means that we
    // need to atleast remove two elements from the array to
    // obtain minimum possible bitwise OR but in the
    // question we need to remove exactly one element.
 
    int sum = 0;
    if (first_index == -1) {
        for (int i = 31; i >= 0; i--) {
            sum = sum | arr[i];
        }
    }
    else {
 
        // Calculating the bitwise OR of all the bits that
        // are set excluding "first_index
        for (int i = 0; i < n; i++) {
            if ((arr[i] & (1 << first_index))) {
                continue;
            }
            else {
                sum = sum | arr[i];
            }
        }
    }
    return sum;
}
 
// Driver code.
int main()
{
 
    int a[] = { 4, 9, 8 };
    int n = sizeof(a) / sizeof(a[0]);
 
    int ans = minOR(a, n);
    cout << ans << endl;
}


Java




// Java implementation of the above approach
import java.util.*;
public class GFG {
 
  static int minOR(int[] arr, int n)
  {
    // Helper array where helper[i] will store the
    // number of elements in the array having the i'th
    // bit set
    int[] helper = new int[32];
    for (int i = 0; i < 32; i++) {
      helper[i] = 0;
    }
 
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < 32; j++) {
 
        // checking if the i'th bit is set
        if ((arr[i] & (1 << j)) != 0) {
          helper[j]++;
        }
      }
    }
 
    // Traverse the helper array from most significant
    // bit to find out the first index i where helper[i]
    // = 1. this means that there is only one element.
    // in the array having i'th bit as set. Let's say
    // this element as current. Since we are traversing
    // the array from most significant bit removing
    // current element will minimize the bitwise OR of
    // the entire array
    int first_index = -1;
 
    for (int i = 31; i >= 0; i--) {
      if (helper[i] == 1) {
        first_index = i;
        break;
      }
    }
 
    // If there is no such element for which helper[i] =
    // 1, it means that either helper[i] = 0 or
    // helper[i] >= 2 for i'th index. if helper[i] >=2
    // this means that we need to atleast remove two
    // elements from the array to obtain minimum
    // possible bitwise OR but in the question we need
    // to remove exactly one element.
 
    int sum = 0;
    if (first_index == -1) {
      for (int i = 31; i >= 0; i--) {
        sum = sum | arr[i];
      }
    }
    else {
 
      // Calculating the bitwise OR of all the bits
      // that are set excluding "first_index
      for (int i = 0; i < n; i++) {
        if ((arr[i] & (1 << first_index)) != 0) {
          continue;
        }
        else {
          sum = sum | arr[i];
        }
      }
    }
    return sum;
  }
 
  // Driver code.
  public static void main(String args[])
  {
 
    int[] a = { 4, 9, 8 };
    int n = a.length;
 
    int ans = minOR(a, n);
    System.out.println(ans);
  }
}
 
// This code is contributed by Samim Hossain Mondal.


C#




// C# implementation of the above approach
using System;
class GFG {
 
  static int minOR(int[] arr, int n)
  {
    // Helper array where helper[i] will store the
    // number of elements in the array having the i'th
    // bit set
    int[] helper = new int[32];
    for (int i = 0; i < 32; i++) {
      helper[i] = 0;
    }
 
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < 32; j++)
      {
         
        // checking if the i'th bit is set
        if ((arr[i] & (1 << j)) != 0) {
          helper[j]++;
        }
      }
    }
 
    // Traverse the helper array from most significant
    // bit to find out the first index i where helper[i]
    // = 1. this means that there is only one element.
    // in the array having i'th bit as set. Let's say
    // this element as current. Since we are traversing
    // the array from most significant bit removing
    // current element will minimize the bitwise OR of
    // the entire array
    int first_index = -1;
 
    for (int i = 31; i >= 0; i--) {
      if (helper[i] == 1) {
        first_index = i;
        break;
      }
    }
 
    // If there is no such element for which helper[i] =
    // 1, it means that either helper[i] = 0 or
    // helper[i] >= 2 for i'th index. if helper[i] >=2
    // this means that we need to atleast remove two
    // elements from the array to obtain minimum
    // possible bitwise OR but in the question we need
    // to remove exactly one element.
 
    int sum = 0;
    if (first_index == -1) {
      for (int i = 31; i >= 0; i--) {
        sum = sum | arr[i];
      }
    }
    else {
 
      // Calculating the bitwise OR of all the bits
      // that are set excluding "first_index
      for (int i = 0; i < n; i++) {
        if ((arr[i] & (1 << first_index)) != 0) {
          continue;
        }
        else {
          sum = sum | arr[i];
        }
      }
    }
    return sum;
  }
 
  // Driver code.
  public static void Main()
  {
 
    int[] a = { 4, 9, 8 };
    int n = a.Length;
 
    int ans = minOR(a, n);
    Console.WriteLine(ans);
  }
}
 
// This code is contributed by Samim Hossain Mondal.


Javascript




// Javascript implementation of the above approach
 
function minOR(arr, n)
{
    // Helper array where helper[i] will store the number of
    // elements in the array having the i'th bit set
    let helper=new Array(32).fill(0);
    for (let i = 0; i < n; i++) {
        for (let j = 0; j < 32; j++) {
            // checking if the i'th bit is set
            if ((arr[i] & (1 << j))) {
                helper[j]++;
            }
        }
    }
 
    // Traverse the helper array from most significant bit
    // to find out the first index i where helper[i] = 1.
    // this means that there is only one element. in the
    // array having i'th bit as set. Let's say this element
    // as current. Since we are traversing the array from
    // most significant bit removing current element will
    // minimize the bitwise OR of the entire array
    let first_index = -1;
 
    for (let i = 31; i >= 0; i--) {
        if (helper[i] == 1) {
            first_index = i;
            break;
        }
    }
 
    // If there is no such element for which helper[i] = 1,
    // it means that either helper[i] = 0 or helper[i] >= 2
    // for i'th index. if helper[i] >=2 this means that we
    // need to atleast remove two elements from the array to
    // obtain minimum possible bitwise OR but in the
    // question we need to remove exactly one element.
 
    let sum = 0;
    if (first_index == -1) {
        for (let i = 31; i >= 0; i--) {
            sum = sum | arr[i];
        }
    }
    else {
 
        // Calculating the bitwise OR of all the bits that
        // are set excluding "first_index
        for (let i = 0; i < n; i++) {
            if ((arr[i] & (1 << first_index))) {
                continue;
            }
            else {
                sum = sum | arr[i];
            }
        }
    }
    return sum;
}
 
// Driver code.
 
    let a = [ 4, 9, 8 ];
    let n = a.length;
 
    let ans = minOR(a, n);
    console.log(ans);


Python3




# python implementation of the above approach
 
def minOR(arr, n):
    # Helper array where helper[i] will store the number of
    # elements in the array having the i'th bit set
    helper=[0]*32;
    for i in range(0,n):
        for j in range(0,32):
            # checking if the i'th bit is set
            if ((arr[i] & (1 << j))):
                helper[j]+=1;
 
    # Traverse the helper array from most significant bit
    # to find out the first index i where helper[i] = 1.
    # this means that there is only one element. in the
    # array having i'th bit as set. Let's say this element
    # as current. Since we are traversing the array from
    # most significant bit removing current element will
    # minimize the bitwise OR of the entire array
    first_index = -1;
     
    i=31;
    while(i>=0):
        if (helper[i] == 1):
            first_index = i;
            break;
        i=i-1;
         
    # If there is no such element for which helper[i] = 1,
    # it means that either helper[i] = 0 or helper[i] >= 2
    # for i'th index. if helper[i] >=2 this means that we
    # need to atleast remove two elements from the array to
    # obtain minimum possible bitwise OR but in the
    # question we need to remove exactly one element.
 
    sum = 0;
    if (first_index == -1):
        i=31;
        while(i>=0):
            sum = sum | arr[i];
            i-=1
         
    else:
 
        # Calculating the bitwise OR of all the bits that
        # are set excluding "first_index
        for i in range(0,n):
            if ((arr[i] & (1 << first_index))) :
                continue;
             
            else:
                sum = sum | arr[i];
             
    return sum;
 
# Driver code.
 
a = [ 4, 9, 8 ];
n = len(a);
 
ans = minOR(a, n);
print(ans);


Output

9

Time Complexity: O(N)
Auxiliary Space: O(1)



Last Updated : 30 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads