Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Count the distinct values taken by the bitwise OR of all contiguous subarrays.

Problem: Count the distinct values taken by the bitwise OR of all contiguous subarrays.
def distinct_or(a):
    res, cur = set(), set()
    for x in a:
        cur = {x | y for y in cur} | {x}
        res |= cur
    return len(res), sorted(res)
print(distinct_or([1, 2, 4]))
What is printed?
  1. A. (6, [1, 2, 3, 4, 6, 7])
  2. B. (7, [1, 2, 3, 4, 5, 6, 7])
  3. C. (6, [1, 2, 3, 4, 5, 7])
  4. D. (3, [1, 3, 7])

Correct answer: A. (6, [1, 2, 3, 4, 6, 7])

The ORs of subarrays ending at i form a set of at most ~32 values, because each extension can only add bits. [1, 2, 4]: subarrays give 1, 2, 4, 3, 6, 7 – 5 (1 | 4) is never contiguous. O(n · 32).

More Coding Interview Problems questions

Exams that ask this topic