Distinct OR values of increasing subsequences
I was asked this
No reports yet. Sign in to say where you were asked it.
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^40 <= 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
0for 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
xin order: for every reachable valueowhose smallest last element is< x,o | xbecomes reachable with last elementx(keep the minimum); the empty subsequence starts with0and no last element. -
O(n · 1024)time, about 10^7 steps, andO(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
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
