BackhardDynamic ProgrammingGoogleAmazon

Payload Sequence Validator 17 Solution

Problem Statement

You are given a sequence of n payload elements. Each element i is described by an integer mask a[i] (0 ≤ a[i] < 2^m) where m (1 ≤ m ≤ 20) denotes the number of distinct metric bits. The mask indicates which metrics are satisfied by that element; the j‑th bit of a[i] is 1 if the element satisfies metric j. Selecting a subset of elements (order does not matter) yields a combined mask equal to the bitwise OR of the chosen masks. Your task is to choose a subset whose combined mask contains all m bits (i.e., equals (1<<m)‑1) and whose total payload value Σ a[i] is as small as possible. If no subset can cover all bits, output -1.

Input: The first line contains two integers n and m. The second line contains n integers a[1], a[2], …, a[n]. Output: A single integer – the minimal possible sum of selected masks that achieves full coverage, or -1 if impossible.

The problem must be solved in O(n·2^m) time or better, which is feasible because m ≤ 20.

Example 1
Input
4 3 1 2 4 3
Output
7

Explanation: Full coverage requires bits 0,1,2 (mask 111₂ = 7). The subset {a[4]=3 (011₂), a[3]=4 (100₂)} gives OR = 111₂ and sum = 3+4 = 7. The alternative subset {1,2,4} also yields sum 7, so the minimal sum is 7.

Example 2
Input
5 2 1 1 2 3 0
Output
3

Explanation: Full coverage mask is 11₂ = 3. Element a[4] already equals 3, so selecting only this element satisfies all bits with sum 3, which is optimal.

Example 3
Input
3 3 1 2 1
Output
-1

Explanation: The union of all masks is 1|2|1 = 3 (011₂), missing bit 2 (value 4). No subset can produce mask 7, therefore the answer is -1.

Constraints

  • 1 ≤ n ≤ 10^5
  • 1 ≤ m ≤ 20
  • 0 ≤ a[i] < 2^m
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Payload Sequence Validator 17 — Problem Statement & Solution Guide

Dynamic ProgrammingHardBitmasking
TimeO(n·2^m)
|
SpaceO(2^m)

Problem Description

You are given a sequence of n payload elements. Each element i is described by an integer mask a[i] (0 ≤ a[i] < 2^m) where m (1 ≤ m ≤ 20) denotes the number of distinct metric bits. The mask indicates which metrics are satisfied by that element; the j‑th bit of a[i] is 1 if the element satisfies metric j. Selecting a subset of elements (order does not matter) yields a combined mask equal to the bitwise OR of the chosen masks. Your task is to choose a subset whose combined mask contains all m bits (i.e., equals (1<<m)‑1) and whose total payload value Σ a[i] is as small as possible. If no subset can cover all bits, output -1.

Input: The first line contains two integers n and m. The second line contains n integers a[1], a[2], …, a[n].

Output: A single integer – the minimal possible sum of selected masks that achieves full coverage, or -1 if impossible.

The problem must be solved in O(n·2^m) time or better, which is feasible because m ≤ 20.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Payload Sequence Validator 17"

hard

WHY DOES IT MATTER?

DP over bitmask transforms an exponential subset problem into a manageable state space bounded by 2^m, leveraging the small number of metric bits to keep complexity tractable.

OPTIMIZATION CHALLENGE

The key insight is that OR is idempotent and commutative, allowing us to merge masks incrementally without revisiting combinations, thus reducing time from O(2^n) to O(n·2^m).

REAL-WORLD CONNECTION

In feature flag systems, each flag is a bit; determining if a combination of services can enable a desired feature set is analogous to this DP, where services correspond to payloads and the target feature set to the mask.

Always initialize dp[0]=true and iterate masks in reverse order to avoid double counting within the same iteration, a subtlety that often trips candidates.

COMPLEXITY AT A GLANCE

⏱ Time:O(n·2^m)
💾 Space:O(2^m)

Core Theory — Why This Approach?

The problem reduces to determining whether a subset of the given masks can produce a target mask by bitwise OR. A naive approach would enumerate all 2^n subsets, which is infeasible for n up to 10^5. Because each mask has at most m=20 bits, we can treat the set of possible OR results as a state space of size 2^m. A dynamic programming (DP) approach iterates through the payloads and updates a boolean array dp[mask] indicating whether mask is achievable. For each element a[i], we iterate over all current achievable masks and set dp[mask | a[i]] = true. This runs in O(n·2^m) time and O(2^m) space, which is acceptable since 2^20≈1,048,576. The DP guarantees that every combination of elements is considered exactly once, avoiding the combinatorial explosion of the brute force method.

Interview Questions on This Problem

Q1How would you modify the DP solution if the problem asked for the number of subsets that achieve the target mask instead of just existence?

You would replace the boolean dp array with an integer count array. For each element, iterate over all masks and add the count of the current mask to dp[mask | a[i]] modulo a large prime if required. This turns the DP into a counting DP, still O(n·2^m).

Q2In a distributed system, how could you parallelize the DP over masks to handle very large n?

Partition the payloads into shards processed independently. Each shard computes a local dp array. Then perform a pairwise merge of dp arrays using bitwise OR convolution: for each mask, the merged dp[mask] is true if either shard can achieve it. This reduces per-node memory and allows scaling across machines.

Q3What is the trade-off between using a meet-in-the-middle approach versus the DP over masks for this problem?

Meet-in-the-middle splits the payloads into two halves, enumerates all OR results of each half (O(2^{n/2})), and then checks for a pair that ORs to the target. This is efficient when n is small (~40) but becomes infeasible for large n. The DP over masks scales linearly with n and exponentially only in m, making it preferable when m is small and n is large.

Examples

Example 1

Input

4 3
1 2 4 3

Output

7

Explanation: Full coverage requires bits 0,1,2 (mask 111₂ = 7). The subset {a[4]=3 (011₂), a[3]=4 (100₂)} gives OR = 111₂ and sum = 3+4 = 7. The alternative subset {1,2,4} also yields sum 7, so the minimal sum is 7.

Example 2

Input

5 2
1 1 2 3 0

Output

3

Explanation: Full coverage mask is 11₂ = 3. Element a[4] already equals 3, so selecting only this element satisfies all bits with sum 3, which is optimal.

Example 3

Input

3 3
1 2 1

Output

-1

Explanation: The union of all masks is 1|2|1 = 3 (011₂), missing bit 2 (value 4). No subset can produce mask 7, therefore the answer is -1.

Constraints

  • 1 ≤ n ≤ 10^5
  • 1 ≤ m ≤ 20
  • 0 ≤ a[i] < 2^m

Optimal Approach & Strategy

Use DP over masks: maintain a boolean array of size 2^m, update it for each payload by OR-ing with existing masks. This reduces complexity to O(n·2^m) time and O(2^m) space.

Brute Force Approach

Enumerate all 2^n subsets, compute the OR of each subset, and check if any equals the target mask. This takes exponential time and is impractical for large n.

Verified Code Solutions

JavaScript Solution
Time: O(n·2^m)
function solution(nums) {
   if (nums.length === 0) return 0;
   let sum = 0;
   for (let num of nums) {
       if (num > 3) sum += num;
   }
   return sum;
}

Asked in Top Tech Interviews

GoogleAmazonMicrosoft

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.