Maximum OR — LeetCode 2680 Python Solution

MediumGreedyBit ManipulationArrayPrefix Sum
Problem
#2680
Pattern
Prefix Sum
Reading time
2 min

The problem

You are given a 0-indexed integer array nums of length n and an integer k. In an operation, you can choose an element and multiply it by 2.

Example

Input
nums = [12,9], k = 1
Output
30
Explanation
If we apply the operation to index 1, our new array nums will be equal to [12,18]. Thus, we return the bitwise or of 12 and 18, which is 30.

Python solution

Python
class Solution:
    def maximumOr(self, nums: List[int], k: int) -> int:
        n = len(nums)
        suf = [0] * (n + 1)
        for i in range(n - 1, -1, -1):
            suf[i] = suf[i + 1] | nums[i]
        ans = pre = 0
        for i, x in enumerate(nums):
            ans = max(ans, pre | (x << k) | suf[i + 1])
            pre |= x
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 2680. Maximum OR is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2680. Maximum OR?
LeetCode 2680. Maximum OR is rated Medium on LeetCode.
What is the time complexity of LeetCode 2680. Maximum OR?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2680. Maximum OR?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2680. Maximum OR cover?
LeetCode 2680. Maximum OR is tagged Greedy, Bit Manipulation, Array and Prefix Sum 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