Count Number of Maximum Bitwise-OR Subsets — LeetCode 2044 Python Solution

MediumBit ManipulationArrayBacktrackingEnumeration
Problem
#2044
Reading time
3 min

The problem

Given an integer array nums, find the maximum possible bitwise OR of a subset of nums and return the number of different non-empty subsets with the maximum bitwise OR. An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b.

Example

Input
nums = [3,1]
Output
2
Explanation
The maximum possible bitwise OR of a subset is 3. There are 2 subsets with a bitwise OR of 3:

Python solution

Python
class Solution:
    def countMaxOrSubsets(self, nums: List[int]) -> int:
        def dfs(i, t):
            nonlocal ans, mx
            if i == len(nums):
                if t == mx:
                    ans += 1
                return
            dfs(i + 1, t)
            dfs(i + 1, t | nums[i])

        ans = 0
        mx = reduce(lambda x, y: x | y, nums)
        dfs(0, 0)
        return ans

Complexity

MeasureComplexity
TimeO(2^n)
SpaceO(n), where n is the length of the array \textit{nums} auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 2044. Count Number of Maximum Bitwise-OR Subsets is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2044. Count Number of Maximum Bitwise-OR Subsets?
LeetCode 2044. Count Number of Maximum Bitwise-OR Subsets is rated Medium on LeetCode.
What is the time complexity of LeetCode 2044. Count Number of Maximum Bitwise-OR Subsets?
The Python solution on this page runs in O(2^n).
What is the space complexity of LeetCode 2044. Count Number of Maximum Bitwise-OR Subsets?
The Python solution on this page uses O(n), where n is the length of the array \textit{nums} auxiliary space.
What topics does LeetCode 2044. Count Number of Maximum Bitwise-OR Subsets cover?
LeetCode 2044. Count Number of Maximum Bitwise-OR Subsets is tagged Bit Manipulation, Array, Backtracking and Enumeration on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview