Find bitwise OR of all possible sub-arrays
Last Updated :
11 Jul, 2025
Given an array A of size N where, 1\leq N \leq 10^{5} . The task is to find the OR of all possible sub-arrays of A and then the OR of all these results.
Examples:
Input : 1 4 6
Output : 7
All possible subarrays are
{1}, {1, 4}, {4, 6} and {1, 4, 6}
ORs of these subarrays are 1, 5, 6
and 7. OR of these ORs is 7.
Input : 10 100 1000
Output : 1006
Approach: In SET 1 we have seen how to find bitwise AND of all possible subarrays. A similar approach is also applicable here.
The Naive solution is to find the OR of all the sub-arrays and then output the OR of their results. This will lead to O(N2) solution.
C++
#include <bits/stdc++.h>
using namespace std;
int OR(vector<int>& arr) {
int n = arr.size();
int res = 0;
for (int i = 0; i < n; i++) {
int curr = 0;
for (int j = i; j < n; j++) {
curr |= arr[j];
res |= curr;
}
}
return res;
}
int main() {
vector<int> arr1 = {1, 4, 6};
cout << OR(arr1) << endl;
vector<int> arr2 = {10, 100, 1000};
cout << OR(arr2) << endl;
return 0;
}
Java
import java.util.*;
class Main {
static int OR(List<Integer> arr) {
int n = arr.size();
int res = 0;
for (int i = 0; i < n; i++) {
int curr = 0;
for (int j = i; j < n; j++) {
curr |= arr.get(j);
res |= curr;
}
}
return res;
}
public static void main(String[] args) {
List<Integer> arr1 = new ArrayList<>(Arrays.asList(1, 4, 6));
System.out.println(OR(arr1));
List<Integer> arr2 = new ArrayList<>(Arrays.asList(10, 100, 1000));
System.out.println(OR(arr2));
}
}
Python3
def OR(arr):
n = len(arr)
res = 0
for i in range(n):
curr = 0
for j in range(i, n):
curr |= arr[j]
res |= curr
return res
arr1 = [1,4,6]
print(OR(arr1))
arr2 = [10,100,1000]
print(OR(arr2))
C#
using System;
using System.Collections.Generic;
class Program {
static int OR(List<int> arr) {
int n = arr.Count;
int res = 0;
for (int i = 0; i < n; i++) {
int curr = 0;
for (int j = i; j < n; j++) {
curr |= arr[j];
res |= curr;
}
}
return res;
}
static void Main(string[] args) {
List<int> arr1 = new List<int>{1, 4, 6};
Console.WriteLine(OR(arr1));
List<int> arr2 = new List<int>{10, 100, 1000};
Console.WriteLine(OR(arr2));
}
}
JavaScript
function OR(arr) {
const n = arr.length;
let res = 0;
for (let i = 0; i < n; i++) {
let curr = 0;
for (let j = i; j < n; j++) {
curr |= arr[j];
res |= curr;
}
}
return res;
}
console.log(OR([1, 4,6]));
Efficient Solution: Using the property that X\|X\|...\|X=X i:e it doesn't matter how many times an element comes, it's OR will be counted as one only. Thus our problem boils down to finding the OR of all the elements of the array.
Implementation:
C++
// C++ program to find OR of all the sub-arrays
#include <bits/stdc++.h>
using namespace std;
// function to return OR of sub-arrays
int OR(int a[], int n)
{
int ans = a[0];
for (int i = 1; i < n; ++i)
ans |= a[i];
return ans;
}
// Driver program
int main()
{
int a[] = { 1, 4, 6 };
int n = sizeof(a) / sizeof(a[0]);
// print OR of all subarrays
cout << OR(a, n);
return 0;
}
Java
// Java program to find OR of
// all the sub-arrays
class GFG
{
// function to return OR
// of sub-arrays
static int OR(int a[],int n)
{
int ans = a[0];
int i;
for(i = 1; i < n; i++)
{
ans |= a[i];
}
return ans;
}
// Driver Code
public static void main(String args[])
{
int a[] = { 1, 4, 6};
int n = a.length;
// print OR of all subarrays
System.out.println(OR(a, n));
}
}
// This code is contributed
// by ANKITRAI1
Python3
# Python3 program to find OR of all the sub-arrays
# function to return OR of sub-arrays
def OR(a, n):
ans = a[0]
for i in range(1,n):
ans |= a[i]
return ans
# Driver Code
if __name__=='__main__':
a = [1, 4, 6]
n = len(a)
# print OR of all subarrays
print(OR(a, n))
# This code is contributed
# by Shashank_Sharma
C#
// C# program to find OR of
// all the sub-arrays
using System;
class GFG
{
// function to return OR
// of sub-arrays
static int OR(int[] a, int n)
{
int ans = a[0];
int i;
for(i = 1; i < n; i++)
{
ans |= a[i];
}
return ans;
}
// Driver Code
public static void Main()
{
int[] a = { 1, 4, 6};
int n = a.Length;
// print OR of all subarrays
Console.Write(OR(a, n));
}
}
// This code is contributed
// by ChitraNayal
PHP
<?php
// PHP program to find OR
// of all the sub-arrays
// function to return OR
// of sub-arrays
function O_R($a, $n)
{
$ans = $a[0];
for ($i = 1; $i < $n; ++$i)
$ans |= $a[$i];
return $ans;
}
// Driver Code
$a = array( 1, 4, 6 );
$n = count($a);
// print OR of all subarrays
echo O_R($a, $n);
// This code is contributed
// by inder_verma
?>
JavaScript
<script>
// Javascript program to find OR of all the sub-arrays
// function to return OR of sub-arrays
function OR(a, n)
{
var ans = a[0];
for (var i = 1; i < n; ++i)
ans |= a[i];
return ans;
}
var a = [ 1, 4, 6 ];
var n = a.length;
// print OR of all subarrays
document.write(OR(a, n));
// This code is contributed by SoumikMondal
</script>
Time Complexity: O(N)
Space Complexity: O(1)
Optimal Solution using Prefix Array for finding OR of all possible sub-arrays:-
Approach:-
- Create two arrays prefix_OR and suffix_OR, both of size N, to store the OR values of prefixes and suffixes respectively.
- Initialize the first element of prefix_OR with the first element of the input array, and the last element of suffix_OR with the last element of the input array.
- Traverse the input array from left to right, and fill prefix_OR using the formula prefix_OR[i] = prefix_OR[i-1] | arr[i].
- Traverse the input array from right to left, and fill suffix_OR using the formula suffix_OR[i] = suffix_OR[i+1] | arr[i].
- Initialize a variable res to 0, and traverse the input array. At each index i, calculate prefix_OR[i] | suffix_OR[i], and perform bitwise OR with res.
- Return the final value of res.
Here is the implementation of above approach:-
C++
#include <iostream>
#include <vector>
using namespace std;
int OR(vector<int>& arr) {
int n = arr.size();
vector<int> prefix_OR(n), suffix_OR(n);
prefix_OR[0] = arr[0];
suffix_OR[n - 1] = arr[n - 1];
for (int i = 1; i < n; i++) {
prefix_OR[i] = prefix_OR[i - 1] | arr[i];
}
for (int i = n - 2; i >= 0; i--) {
suffix_OR[i] = suffix_OR[i + 1] | arr[i];
}
int res = 0;
for (int i = 0; i < n; i++) {
res |= prefix_OR[i] | suffix_OR[i];
}
return res;
}
int main() {
vector<int> arr = {1, 4, 6};
cout << OR(arr) << endl;
arr = {10, 100, 1000};
cout << OR(arr) << endl;
return 0;
}
Java
import java.util.*;
public class Main {
public static int OR(int[] arr) {
int n = arr.length;
int[] prefix_OR = new int[n];
int[] suffix_OR = new int[n];
prefix_OR[0] = arr[0];
suffix_OR[n - 1] = arr[n - 1];
for (int i = 1; i < n; i++) {
prefix_OR[i] = prefix_OR[i - 1] | arr[i];
}
for (int i = n - 2; i >= 0; i--) {
suffix_OR[i] = suffix_OR[i + 1] | arr[i];
}
int res = 0;
for (int i = 0; i < n; i++) {
res |= prefix_OR[i] | suffix_OR[i];
}
return res;
}
public static void main(String[] args) {
int[] arr = {1, 4, 6};
System.out.println(OR(arr));
arr = new int[]{10, 100, 1000};
System.out.println(OR(arr));
}
}
Python3
def OR(arr):
n = len(arr)
prefix_OR = [0] * n
suffix_OR = [0] * n
prefix_OR[0] = arr[0]
suffix_OR[n - 1] = arr[n - 1]
for i in range(1, n):
prefix_OR[i] = prefix_OR[i - 1] | arr[i]
for i in range(n - 2, -1, -1):
suffix_OR[i] = suffix_OR[i + 1] | arr[i]
res = 0
for i in range(n):
res |= prefix_OR[i] | suffix_OR[i]
return res
# Driver code
if __name__=='__main__':
arr = [1, 4, 6]
print(OR(arr))
arr = [10, 100, 1000]
print(OR(arr))
C#
using System;
public class Program
{
public static int OR(int[] arr)
{
int n = arr.Length;
int[] prefix_OR = new int[n];
int[] suffix_OR = new int[n];
prefix_OR[0] = arr[0];
suffix_OR[n - 1] = arr[n - 1];
for (int i = 1; i < n; i++)
{
prefix_OR[i] = prefix_OR[i - 1] | arr[i];
}
for (int i = n - 2; i >= 0; i--)
{
suffix_OR[i] = suffix_OR[i + 1] | arr[i];
}
int res = 0;
for (int i = 0; i < n; i++)
{
res |= prefix_OR[i] | suffix_OR[i];
}
return res;
}
public static void Main()
{
int[] arr1 = { 1, 4, 6 };
Console.WriteLine(OR(arr1));
int[] arr2 = { 10, 100, 1000 };
Console.WriteLine(OR(arr2));
}
}
PHP
<?php
function OR($arr) {
$n = count($arr);
$prefix_OR = array();
$suffix_OR = array();
$prefix_OR[0] = $arr[0];
$suffix_OR[$n - 1] = $arr[$n - 1];
for ($i = 1; $i < $n; $i++) {
$prefix_OR[$i] = $prefix_OR[$i - 1] | $arr[$i];
}
for ($i = $n - 2; $i >= 0; $i--) {
$suffix_OR[$i] = $suffix_OR[$i + 1] | $arr[$i];
}
$res = 0;
for ($i = 0; $i < $n; $i++) {
$res |= $prefix_OR[$i] | $suffix_OR[$i];
}
return $res;
}
echo OR([1, 4, 6]);
?>
JavaScript
function OR(arr) {
const n = arr.length;
const prefix_OR = new Array(n);
const suffix_OR = new Array(n);
prefix_OR[0] = arr[0];
suffix_OR[n - 1] = arr[n - 1];
for (let i = 1; i < n; i++) {
prefix_OR[i] = prefix_OR[i - 1] | arr[i];
}
for (let i = n - 2; i >= 0; i--) {
suffix_OR[i] = suffix_OR[i + 1] | arr[i];
}
let res = 0;
for (let i = 0; i < n; i++) {
res |= prefix_OR[i] | suffix_OR[i];
}
return res;
}
console.log(OR([1, 4, 6]));
console.log(OR([10, 100, 1000]));
Time Complexity:
The time complexity of this approach is O(N), where N is the size of the input array.
Space Complexity:
The space complexity of this approach is O(N), where N is the size of the input array, as we are using two extra arrays of size N to store the prefix and suffix OR values.
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