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?- A. (6, [1, 2, 3, 4, 6, 7])
- B. (7, [1, 2, 3, 4, 5, 6, 7])
- C. (6, [1, 2, 3, 4, 5, 7])
- 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
- Problem: Compute the maximum XOR of any two numbers using a greedy prefix-set approach bit by bit. python def maxxor(a): ans = mask = 0…
- Problem: Implement atoi: skip leading spaces, read an optional sign and digits, stop at the first non-digit, clamp to 32-bit range. python…
- Problem: Count the number of ways to climb n stairs taking 1, 2 or 3 steps, modulo 10⁹ + 7. java static long ways3(int n) { long MOD =…
- Problem: A frog jumps from stone 0 to stone n − 1; jumping from i to j (j ≤ i + k) costs |h[i] − h[j]|. Find the minimum cost. python def…
- Problem: Count palindromic substrings (each occurrence counts separately). python def countpal(s): n, c = len(s), 0 for center in range(2…
- Problem: Find the length of the longest arithmetic subsequence. python def longestap(a): dp = [{} for in a]; best = 1 for i in…