← Questions

Distinct OR values of increasing subsequences

0
Scale AICoding

A coding interview question asked at Scale AI. It tests dynamic programming, bit manipulation and subsequences.

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.

Clarifying questions

  • Is the answer always including 0 for the empty subsequence, even for an empty array?
  • Are values limited to < 1024, so every OR value is also below 1024?
  • Should the output be a sorted list of distinct values only, not counts?

What a strong answer covers

  • The key bound: every OR value is in [0, 1024), so there are at most 1024 states, whatever the length of the array.
  • For each OR value, keep the smallest last element of any strictly increasing subsequence that reaches it; a smaller last element dominates, since it can be extended by everything a larger one can.
  • Processing each x in order: for every reachable value o whose smallest last element is < x, o | x becomes reachable with last element x (keep the minimum); the empty subsequence starts with 0 and no last element.
  • O(n · 1024) time, about 10^7 steps, and O(1024) space.
  • Tests: both examples, an empty array, a strictly decreasing array (only single elements), an array with zeros, and a brute force over all subsequences on small random arrays.

Follow-ups

  • Count how many increasing subsequences give each value.
  • Return one subsequence for each value.
  • Non-decreasing instead of strictly increasing.
  • Values up to 2^20: what breaks, and what still works?

Where it's asked

What it tests

dynamic programming · bit manipulation · subsequences

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding