Concatenated Divisibility Problem
Description
LeetCode Problem 3533.
You are given an array of positive integers nums and a positive integer k.
A permutation of nums is said to form a divisible concatenation if, when you concatenate the decimal representations of the numbers in the order specified by the permutation, the resulting number is divisible by k.
Return the lexicographically smallest permutation (when considered as a list of integers) that forms a divisible concatenation. If no such permutation exists, return an empty list.
Example 1:
Input: nums = [3,12,45], k = 5
Output: [3,12,45]
Explanation:
Permutation Concatenated Value Divisible by 5
[3, 12, 45] 31245 Yes
[3, 45, 12] 34512 No
[12, 3, 45] 12345 Yes
[12, 45, 3] 12453 No
[45, 3, 12] 45312 No
[45, 12, 3] 45123 No
The lexicographically smallest permutation that forms a divisible concatenation is [3,12,45].
Example 2:
Input: nums = [10,5], k = 10
Output: [5,10]
Explanation:
Permutation Concatenated Value Divisible by 10
[5, 10] 510 Yes
[10, 5] 105 No
The lexicographically smallest permutation that forms a divisible concatenation is [5,10].
Example 3:
Input: nums = [1,2,3], k = 5
Output: []
Explanation:
Since no permutation of nums forms a valid divisible concatenation, return an empty list.
Constraints:
1 <= nums.length <= 131 <= nums[i] <= 10^51 <= k <= 100
Solution
Approach: Bitmask DP
Sort nums so that choosing the smallest valid number at each step gives the lexicographically smallest permutation. Concatenating a number x onto a prefix with remainder r gives remainder (r * 10^len(x) + x) mod k, so only the set of used numbers and the current remainder matter. Compute ok[mask][r], which says whether the remaining numbers can be appended to reach remainder 0, going from the full mask down to the empty one. If ok[0][0] is false, return an empty list. Otherwise rebuild the answer greedily: at each step take the smallest unused number whose resulting state is still ok.
Complexity: O(2^n * n * k) time and O(2^n * k) extra space, where n is the length of nums.
class Solution:
def concatenatedDivisibility(self, nums: List[int], k: int) -> List[int]:
nums = sorted(nums)
n = len(nums)
pw = [pow(10, len(str(x)), k) for x in nums]
full = (1 << n) - 1
# ok[mask][r]: starting from used set mask with remainder r, can we finish with remainder 0
ok = [[False] * k for _ in range(full + 1)]
ok[full][0] = True
for mask in range(full - 1, -1, -1):
row = ok[mask]
for i in range(n):
if (mask >> i) & 1:
continue
nxt = ok[mask | (1 << i)]
p, x = pw[i], nums[i] % k
for r in range(k):
if not row[r] and nxt[(r * p + x) % k]:
row[r] = True
if not ok[0][0]:
return []
ans = []
mask = r = 0
for _ in range(n):
for i in range(n):
if (mask >> i) & 1:
continue
nr = (r * pw[i] + nums[i]) % k
if ok[mask | (1 << i)][nr]:
ans.append(nums[i])
mask |= 1 << i
r = nr
break
return ans