LeetCode #3444 — HARD

Minimum Increments for Target Multiples in an Array

Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.

Solve on LeetCode
The Problem

Problem Statement

You are given two arrays, nums and target.

In a single operation, you may increment any element of nums by 1.

Return the minimum number of operations required so that each element in target has at least one multiple in nums.

Example 1:

Input: nums = [1,2,3], target = [4]

Output: 1

Explanation:

The minimum number of operations required to satisfy the condition is 1.

  • Increment 3 to 4 with just one operation, making 4 a multiple of itself.

Example 2:

Input: nums = [8,4], target = [10,5]

Output: 2

Explanation:

The minimum number of operations required to satisfy the condition is 2.

  • Increment 8 to 10 with 2 operations, making 10 a multiple of both 5 and 10.

Example 3:

Input: nums = [7,9,10], target = [7]

Output: 0

Explanation:

Target 7 already has a multiple in nums, so no additional operations are needed.

Constraints:

  • 1 <= nums.length <= 5 * 104
  • 1 <= target.length <= 4
  • target.length <= nums.length
  • 1 <= nums[i], target[i] <= 104
Patterns Used

Roadmap

  1. Brute Force Baseline
  2. Core Insight
  3. Algorithm Walkthrough
  4. Edge Cases
  5. Full Annotated Code
  6. Interactive Study Demo
  7. Complexity Analysis
Step 01

Brute Force Baseline

Problem summary: You are given two arrays, nums and target. In a single operation, you may increment any element of nums by 1. Return the minimum number of operations required so that each element in target has at least one multiple in nums.

Baseline thinking

Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.

Pattern signal: Array · Math · Dynamic Programming · Bit Manipulation

Example 1

[1,2,3]
[4]

Example 2

[8,4]
[10,5]

Example 3

[7,9,10]
[7]
Step 02

Core Insight

What unlocks the optimal approach

  • Use bitmask dynamic programming.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03

Algorithm Walkthrough

Iteration Checklist

  1. Define state (indices, window, stack, map, DP cell, or recursion frame).
  2. Apply one transition step and update the invariant.
  3. Record answer candidate when condition is met.
  4. Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04

Edge Cases

Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05

Full Annotated Code

Source-backed implementations are provided below for direct study and interview prep.

// Accepted solution for LeetCode #3444: Minimum Increments for Target Multiples in an Array
class Solution {
  public int minimumIncrements(int[] nums, int[] target) {
    final int maxMask = 1 << target.length;
    Map<Integer, Long> maskToLcm = new HashMap<>();

    for (int mask = 1; mask < maxMask; ++mask) {
      List<Integer> subset = getSubset(mask, target);
      maskToLcm.put(mask, getLcm(subset));
    }

    // dp[mask] := the minimum number of increments to make each number in the
    // subset of target have at least one number that is a multiple in `num`,
    // where `mask` is the bitmask of the subset of target
    long[] dp = new long[maxMask];
    Arrays.fill(dp, Long.MAX_VALUE);
    dp[0] = 0;

    for (final int num : nums) {
      // maskToCost := (mask, cost), where `mask` is the bitmask of the subset
      // of target and `cost` is the minimum number of increments to make each
      // number in the subset of target have at least one number that is a
      // multiple in `num`
      List<Pair<Integer, Long>> maskToCost = new ArrayList<>();
      for (Map.Entry<Integer, Long> entry : maskToLcm.entrySet()) {
        final int mask = entry.getKey();
        final long lcm = entry.getValue();
        final long remainder = num % lcm;
        maskToCost.add(new Pair<>(mask, remainder == 0 ? 0 : lcm - remainder));
      }
      long[] newDp = dp.clone();
      for (int prevMask = 0; prevMask < maxMask; ++prevMask) {
        if (dp[prevMask] == Long.MAX_VALUE)
          continue;
        for (Pair<Integer, Long> pair : maskToCost) {
          final int mask = pair.getKey();
          final long cost = pair.getValue();
          final int newMask = prevMask | mask;
          newDp[newMask] = Math.min(newDp[newMask], dp[prevMask] + cost);
        }
      }
      dp = newDp;
    }

    return dp[maxMask - 1] == Long.MAX_VALUE ? -1 : (int) dp[maxMask - 1];
  }

  private List<Integer> getSubset(int mask, int[] target) {
    List<Integer> subset = new ArrayList<>();
    for (int i = 0; i < target.length; ++i)
      if ((mask >> i & 1) == 1)
        subset.add(target[i]);
    return subset;
  }

  private long getLcm(List<Integer> nums) {
    long res = 1;
    for (final int num : nums)
      res = lcm(res, num);
    return res;
  }

  private long lcm(long a, long b) {
    return a * b / gcd(a, b);
  }

  private long gcd(long a, long b) {
    return b == 0 ? a : gcd(b, a % b);
  }
}
Step 06

Interactive Study Demo

Use this to step through a reusable interview workflow for this problem.

Press Step or Run All to begin.
Step 07

Complexity Analysis

Time
O(n × m)
Space
O(n × m)

Approach Breakdown

RECURSIVE
O(2ⁿ) time
O(n) space

Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.

DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space

Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.

Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes

Common Mistakes

Review these before coding to avoid predictable interview regressions.

Off-by-one on range boundaries

Wrong move: Loop endpoints miss first/last candidate.

Usually fails on: Fails on minimal arrays and exact-boundary answers.

Fix: Re-derive loops from inclusive/exclusive ranges before coding.

Overflow in intermediate arithmetic

Wrong move: Temporary multiplications exceed integer bounds.

Usually fails on: Large inputs wrap around unexpectedly.

Fix: Use wider types, modular arithmetic, or rearranged operations.

State misses one required dimension

Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.

Usually fails on: Correctness breaks on cases that differ only in hidden state.

Fix: Define state so each unique subproblem maps to one DP cell.