Distinct OR values of increasing subsequences

0
Sign in

Given an integer array arr, define the goodness of a sequence as the bitwise OR of all its elements. The goodness of the empty sequence is 0.

A subsequence keeps elements in their original order but may skip any of them. Consider every strictly increasing subsequence of arr (each element is strictly greater than the one before it). The empty subsequence counts as strictly increasing.

Return every distinct goodness value that some strictly increasing subsequence can have, sorted in ascending order.

def distinct_goodness(arr: list[int]) -> list[int]: ...

Constraints

  • 0 <= len(arr) <= 10^4
  • 0 <= arr[i] < 1024

Example 1

arr = [2, 1, 4]
output = [0, 1, 2, 4, 5, 6]

The increasing subsequences are [], [2], [1], [4], [2, 4] and [1, 4], with goodness 0, 2, 1, 4, 6 and 5. [2, 1] is not increasing, so 3 is not reachable.

Example 2

arr = [3, 3, 3]
output = [0, 3]

Equal neighbours cannot both appear, so only [] and [3] count.

Scale AICodingMedium

Sign in to see the worked answer

The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.