#3533

Concatenated Divisibility

Hard
ArrayDynamic ProgrammingBit ManipulationBitmaskBacktrackingDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n!)
O(n * 2^n)
Space
O(n)
O(2^n)
💡

Intuition

Time O(n * 2^n)Space O(2^n)

Use dynamic programming with bitmasks to track used numbers and their concatenated value's modulus. This reduces the number of checks significantly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP table where dp[mask] holds the smallest concatenated number mod k for the bitmask 'mask'.
  2. 2Step 2: Iterate through all masks and for each number not in the mask, update the new mask and calculate the new mod value.
  3. 3Step 3: After filling the DP table, find the smallest permutation that gives a mod value of 0.
solution.py17 lines
1from itertools import permutations
2
3def divisible_permutation(nums, k):
4    n = len(nums)
5    dp = [None] * (1 << n)
6    dp[0] = ''
7    for mask in range(1 << n):
8        for i in range(n):
9            if not (mask & (1 << i)):
10                new_mask = mask | (1 << i)
11                new_num = dp[mask] + str(nums[i]) if dp[mask] is not None else str(nums[i])
12                if dp[new_mask] is None or new_num < dp[new_mask]:
13                    dp[new_mask] = new_num
14    for mask in range(1 << n):
15        if dp[mask] is not None and int(dp[mask]) % k == 0:
16            return sorted([nums[i] for i in range(n) if mask & (1 << i)])
17    return []

Complexity note: Each state in DP is computed in O(n) time, and there are 2^n states.

  • 1Permutations can be costly; use bitmasks to optimize.
  • 2Divisibility can be checked using modular arithmetic.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.