Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Sum of all subsequences of an array
Next article icon

Bitwise OR of sum of all subsequences of an array

Last Updated : 23 Apr, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] of length N, the task is to find the Bitwise OR of the sum of all possible subsequences from the given array.

Examples:

Input: arr[] = {4, 2, 5}
Output: 15
Explanation: All subsequences from the given array and their corresponding sums:
{4} – 4
{2} – 2
{5} – 5
{4, 2} – 6
{4, 5} – 9
{2, 5} – 7
{4, 2, 5} -11
Therefore, the Bitwise OR of all sums = 4 | 2 | 5 | 6 | 9 | 7 | 11 = 15.

Input: arr[] = {1, 9, 8}
Output: 27
Explanation: All subsequences from the given array and their corresponding sums:
{1} – 1
{9} – 9
{8} – 8
{1, 9} – 10
{9, 8} – 17
{1, 8} – 9
{1, 9, 8} – 18
Therefore, Bitwise OR of all sums = 1 | 9 | 8 | 10 | 17 | 9 | 18 = 27.

Naive Approach: The simplest approach is to generate all possible subsequences from the given array and find their respective sums. Now, after calculating their sums, print the Bitwise OR of all the sums obtained. 

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

Efficient approach: To optimize the above approach, the idea is based on the following observations:

  • All the set bits in the array elements are also set in the final result.
  • All the bits set in the prefix sum array of the given array are also set in the final result.

Follow the steps below to solve the above problem:

  • Initialize a variable result with 0 that stores the Bitwise OR of the sum of each subsequence of the given array arr[].
  • Initialize a variable prefixSum with 0 that stores the prefix sum of arr[] at any instant.
  • Iterate over the array elements in the range [0, N] using variable i.
    • Update prefixSumas prefixSum+= arr[i].
    • Update result as result | = arr[i] | prefixSum.
  • After the above steps, print the value of the result as the answer.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate Bitwise OR of
// sums of all subsequences
int findOR(int nums[], int N)
{
    // Stores the prefix sum of nums[]
    int prefix_sum = 0;
 
    // Stores the bitwise OR of
    // sum of each subsequence
    int result = 0;
 
    // Iterate through array nums[]
    for (int i = 0; i < N; i++) {
 
        // Bits set in nums[i] are
        // also set in result
        result |= nums[i];
 
        // Calculate prefix_sum
        prefix_sum += nums[i];
 
        // Bits set in prefix_sum
        // are also set in result
        result |= prefix_sum;
    }
 
    // Return the result
    return result;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 4, 2, 5 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << findOR(arr, N);
 
    return 0;
}
 
 

Java




// Java program for the above approach
import java.util.*;
 
class GFG{
   
// Function to calculate Bitwise OR of
// sums of all subsequences
static int findOR(int nums[], int N)
{
    // Stores the prefix sum of nums[]
    int prefix_sum = 0;
 
    // Stores the bitwise OR of
    // sum of each subsequence
    int result = 0;
 
    // Iterate through array nums[]
    for (int i = 0; i < N; i++) {
 
        // Bits set in nums[i] are
        // also set in result
        result |= nums[i];
 
        // Calculate prefix_sum
        prefix_sum += nums[i];
 
        // Bits set in prefix_sum
        // are also set in result
        result |= prefix_sum;
    }
 
    // Return the result
    return result;
}
 
// Driver Code
public static void main(String[] args)
{
    // Given array arr[]
    int arr[] = { 4, 2, 5 };
    int N = arr.length;
    System.out.print(findOR(arr, N));
}
}
 
 

Python3




# Python3 program for the
# above approach
 
# Function to calculate
# Bitwise OR of sums of
# all subsequences
def findOR(nums,  N):
 
    # Stores the prefix
    # sum of nums[]
    prefix_sum = 0
 
    # Stores the bitwise OR of
    # sum of each subsequence
    result = 0
 
    # Iterate through array nums[]
    for i in range(N):
 
        # Bits set in nums[i] are
        # also set in result
        result |= nums[i]
 
        # Calculate prefix_sum
        prefix_sum += nums[i]
 
        # Bits set in prefix_sum
        # are also set in result
        result |= prefix_sum
 
    # Return the result
    return result
 
# Driver Code
if __name__ == "__main__":
 
    # Given array arr[]
    arr = [4, 2, 5]
 
    N = len(arr)
 
    # Function Call
    print(findOR(arr, N))
 
# This code is contributed by Chitranayal
 
 

C#




// C# program for the above approach
using System;
 
class GFG{
 
// Function to calculate Bitwise OR of
// sums of all subsequences
static int findOR(int[] nums, int N)
{
     
    // Stores the prefix sum of nums[]
    int prefix_sum = 0;
 
    // Stores the bitwise OR of
    // sum of each subsequence
    int result = 0;
 
    // Iterate through array nums[]
    for(int i = 0; i < N; i++)
    {
         
        // Bits set in nums[i] are
        // also set in result
        result |= nums[i];
 
        // Calculate prefix_sum
        prefix_sum += nums[i];
 
        // Bits set in prefix_sum
        // are also set in result
        result |= prefix_sum;
    }
 
    // Return the result
    return result;
}
 
// Driver Code
public static void Main()
{
     
    // Given array arr[]
    int[] arr = { 4, 2, 5 };
     
    // Size of array
    int N = arr.Length;
     
    // Function call
    Console.Write(findOR(arr, N));
}
}
 
// This code is contributed by code_hunt
 
 

Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to calculate Bitwise OR of
// sums of all subsequences
function findOR(nums, N)
{
    // Stores the prefix sum of nums[]
    let prefix_sum = 0;
  
    // Stores the bitwise OR of
    // sum of each subsequence
    let result = 0;
  
    // Iterate through array nums[]
    for (let i = 0; i < N; i++) {
  
        // Bits set in nums[i] are
        // also set in result
        result |= nums[i];
  
        // Calculate prefix_sum
        prefix_sum += nums[i];
  
        // Bits set in prefix_sum
        // are also set in result
        result |= prefix_sum;
    }
  
    // Return the result
    return result;
}
  
// Driver Code
 
   // Given array arr[]
    let arr = [ 4, 2, 5 ];
    let N = arr.length;
    document.write(findOR(arr, N));
   
  // This code is contributed by avijitmondal1998.
</script>
 
 
Output: 
15

 

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



Next Article
Sum of all subsequences of an array

M

ManikantaBandla
Improve
Article Tags :
  • Arrays
  • Bit Magic
  • DSA
  • Mathematical
  • Bitwise-OR
  • prefix-sum
  • subsequence
Practice Tags :
  • Arrays
  • Bit Magic
  • Mathematical
  • prefix-sum

Similar Reads

  • Sum of all subsequences of an array
    Given an array of n integers. Find the sum of all possible subsequences of an array. Examples : Input : arr[] = { 1, 2 } Output : 6 All possible subsequences are {}, {1}, {2} and { 1, 2 } Input : arr[] = { 1, 2, 3 } Output : 24Recommended: Please solve it on “PRACTICE ” first, before moving on to th
    4 min read
  • Find all distinct subset (or subsequence) sums of an array
    Given an array arr[] of size n, the task is to find a distinct sum that can be generated from the subsets of the given sets and return them in increasing order. It is given that the sum of array elements is small. Examples: Input: arr[] = [1, 2]Output: [0, 1, 2, 3]Explanation: Four distinct sums can
    15+ min read
  • Find all distinct subset (or subsequence) sums of an array | Set-2
    Given an array of N positive integers write an efficient function to find the sum of all those integers which can be expressed as the sum of at least one subset of the given array i.e. calculate total sum of each subset whose sum is distinct using only O(sum) extra space. Examples: Input: arr[] = {1
    9 min read
  • Sum of Bitwise-OR of all Submatrices
    Given a NxN matrix, the task is to find the sum of bit-wise OR of all of its rectangular sub-matrices.Examples: Input : arr[][] = {{1, 0, 0}, {0, 0, 0}, {0, 0, 0}} Output : 9 Explanation: All the submatrices starting from the index (0, 0) will have OR value as 1. Thus, ans = 9 Input : arr[][] = {{9,
    14 min read
  • Count subsequences having odd Bitwise OR values in an array
    Given an array arr[] consisting of N positive integers, the task is to find the number of subsequences from the given array whose Bitwise OR value is odd. Examples: Input: arr = [2, 4, 1]Output: 4Explanation: Subsequences with odd Bitwise OR values are {1}, {2, 1}, {4, 1}, {2, 4, 1} Input: arr = [1,
    5 min read
  • Bitwise OR of Bitwise AND of all subarrays of an array
    Given an array arr[] consisting of N positive integers, the task is to find the Bitwise OR of Bitwise AND of all subarrays of the given arrays. Examples: Input: arr[] = {1, 2, 3}Output: 3Explanation:The following are Bitwise AND of all possible subarrays are: {1}, Bitwise AND is 1.{1, 2}, Bitwise AN
    7 min read
  • Sum of bitwise AND of all submatrices
    Given an NxN matrix, the task is to find the sum of bit-wise AND of all of its rectangular sub-matrices. Examples: Input : arr[][] = {{1, 1, 1}, {1, 1, 1}, {1, 1, 1}} Output : 36 Explanation: All the possible submatrices will have AND value 1. Since, there are 36 submatrices in total, ans = 36 Input
    13 min read
  • Sum of Bitwise AND of all pairs possible from two arrays
    Given two arrays A[] and B[] of size N and M respectively, the task is to find the sum of Bitwise AND of all possible unordered pairs (A[i], B[j]) from the two arrays. Examples: Input: A[] = {1, 2} , B[] = {3, 4} Output: 3 Explanation: Bitwise AND of all possible pairs are 1 & 3 = 1 1 & 4 =
    5 min read
  • Sum of all subsequences of a number
    Given a number as string s, find the sum of all the elements present in all possible subsequences of s.Examples : Input : s = "123" Output : 24 Explanation : all possible sub-sequences are 1, 2, 3, {1, 2}, {2, 3}, {1, 3}, {1, 2, 3} which add up to 24 Input : s = "453" Output : 48 Recommended Practic
    14 min read
  • Bitwise OR of Bitwise AND of all subsets of an Array for Q queries
    Given two arrays arr[] of size N and queries[] of size Q, the task is to find the OR of AND of subsets of the array. In each query, you are given an index and a value, you have to replace the value at the given index of the arrays with a given value and print the OR of AND of all subsets of the arra
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences