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.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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] <= 1051 <= k <= 100Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming · Bit Manipulation
[3,12,45] 5
[10,5] 10
[1,2,3] 5
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3533: Concatenated Divisibility
class Solution {
public int[] concatenatedDivisibility(int[] nums, int k) {
final int n = nums.length;
int[] lengths = new int[n];
int[] pows = new int[n];
Arrays.sort(nums);
for (int i = 0; i < n; ++i) {
lengths[i] = String.valueOf(nums[i]).length();
pows[i] = (int) Math.pow(10, lengths[i]) % k;
}
Integer[][] mem = new Integer[1 << n][k];
return dp(nums, pows, mem, k, 0, 0) ? reconstruct(nums, pows, mem, k, 0, 0) : new int[0];
}
// Returns true if there is a way to form a number divisible by `k` using the
// numbers in `nums`, where nums[i] is used iff `mask & (1 << i)`.
private boolean dp(int[] nums, int[] pows, Integer[][] mem, int k, int mask, int mod) {
if (mem[mask][mod] != null)
return mem[mask][mod] == 1;
if (mask == (1 << nums.length) - 1)
return (mem[mask][mod] = mod == 0 ? 1 : 0) == 1;
for (int i = 0; i < nums.length; ++i)
if ((mask >> i & 1) == 0) {
final int newMod = (mod * pows[i] + nums[i]) % k;
if (dp(nums, pows, mem, k, mask | 1 << i, newMod))
return (mem[mask][mod] = 1) == 1;
}
return (mem[mask][mod] = 0) == 1;
}
// Reconstructs the numbers that form a number divisible by `k` using the
// numbers in `nums`, where nums[i] is used iff `mask & (1 << i)`.
private int[] reconstruct(int[] nums, int[] pows, Integer[][] mem, int k, int mask, int mod) {
for (int i = 0; i < nums.length; ++i)
if ((mask >> i & 1) == 0) {
final int newMod = (mod * pows[i] + nums[i]) % k;
if (dp(nums, pows, mem, k, mask | 1 << i, newMod)) {
int[] first = new int[] {nums[i]};
int[] rest = reconstruct(nums, pows, mem, k, mask | 1 << i, newMod);
int[] res = new int[first.length + rest.length];
System.arraycopy(first, 0, res, 0, first.length);
System.arraycopy(rest, 0, res, first.length, rest.length);
return res;
}
}
return new int[0];
}
}
// Accepted solution for LeetCode #3533: Concatenated Divisibility
package main
import (
"math"
"math/bits"
"slices"
"strconv"
)
// https://space.bilibili.com/206214
func concatenatedDivisibility(nums []int, k int) []int {
slices.Sort(nums)
n := len(nums)
pow10 := make([]int, n)
for i, x := range nums {
pow10[i] = int(math.Pow10(len(strconv.Itoa(x))))
}
ans := make([]int, 0, n)
vis := make([][]bool, 1<<n)
for i := range vis {
vis[i] = make([]bool, k)
}
var dfs func(int, int) bool
dfs = func(s, x int) bool {
if s == 0 {
return x == 0
}
if vis[s][x] {
return false
}
vis[s][x] = true
// 枚举在 s 中的下标 i
for t := uint(s); t > 0; t &= t - 1 {
i := bits.TrailingZeros(t)
if dfs(s^1<<i, (x*pow10[i]+nums[i])%k) {
ans = append(ans, nums[i])
return true
}
}
return false
}
if !dfs(1<<n-1, 0) {
return nil
}
slices.Reverse(ans) // nums[i] 是倒序加入答案的,所以要反转
return ans
}
# Accepted solution for LeetCode #3533: Concatenated Divisibility
class Solution:
def concatenatedDivisibility(self, nums: list[int], k: int) -> list[int]:
n = len(nums)
nums.sort()
lengths = [len(str(num)) for num in nums]
pows = [pow(10, length, k) for length in lengths]
@functools.lru_cache(None)
def dp(mask: int, mod: int) -> bool:
"""
Returns True if there is a way to form a number divisible by `k` using the
numbers in `nums`, where nums[i] is used iff `mask & (1 << i)`.
"""
if mask == (1 << n) - 1:
return mod == 0
for i in range(n):
if (mask >> i & 1) == 0:
newMod = (mod * pows[i] + nums[i]) % k
if dp(mask | 1 << i, newMod):
return True
return False
def reconstruct(mask: int, mod: int) -> list[int]:
"""
Reconstructs the numbers that form a number divisible by `k` using the
numbers in `nums`, where nums[i] is used iff `mask & (1 << i)`.
"""
for i in range(n):
if (mask >> i & 1) == 0:
newMod = (mod * pows[i] + nums[i]) % k
if dp(mask | 1 << i, newMod):
return [nums[i]] + reconstruct(mask | 1 << i, newMod)
return []
return reconstruct(0, 0) if dp(0, 0) else []
// Accepted solution for LeetCode #3533: Concatenated Divisibility
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3533: Concatenated Divisibility
// class Solution {
// public int[] concatenatedDivisibility(int[] nums, int k) {
// final int n = nums.length;
// int[] lengths = new int[n];
// int[] pows = new int[n];
//
// Arrays.sort(nums);
//
// for (int i = 0; i < n; ++i) {
// lengths[i] = String.valueOf(nums[i]).length();
// pows[i] = (int) Math.pow(10, lengths[i]) % k;
// }
//
// Integer[][] mem = new Integer[1 << n][k];
// return dp(nums, pows, mem, k, 0, 0) ? reconstruct(nums, pows, mem, k, 0, 0) : new int[0];
// }
//
// // Returns true if there is a way to form a number divisible by `k` using the
// // numbers in `nums`, where nums[i] is used iff `mask & (1 << i)`.
// private boolean dp(int[] nums, int[] pows, Integer[][] mem, int k, int mask, int mod) {
// if (mem[mask][mod] != null)
// return mem[mask][mod] == 1;
// if (mask == (1 << nums.length) - 1)
// return (mem[mask][mod] = mod == 0 ? 1 : 0) == 1;
// for (int i = 0; i < nums.length; ++i)
// if ((mask >> i & 1) == 0) {
// final int newMod = (mod * pows[i] + nums[i]) % k;
// if (dp(nums, pows, mem, k, mask | 1 << i, newMod))
// return (mem[mask][mod] = 1) == 1;
// }
// return (mem[mask][mod] = 0) == 1;
// }
//
// // Reconstructs the numbers that form a number divisible by `k` using the
// // numbers in `nums`, where nums[i] is used iff `mask & (1 << i)`.
// private int[] reconstruct(int[] nums, int[] pows, Integer[][] mem, int k, int mask, int mod) {
// for (int i = 0; i < nums.length; ++i)
// if ((mask >> i & 1) == 0) {
// final int newMod = (mod * pows[i] + nums[i]) % k;
// if (dp(nums, pows, mem, k, mask | 1 << i, newMod)) {
// int[] first = new int[] {nums[i]};
// int[] rest = reconstruct(nums, pows, mem, k, mask | 1 << i, newMod);
// int[] res = new int[first.length + rest.length];
// System.arraycopy(first, 0, res, 0, first.length);
// System.arraycopy(rest, 0, res, first.length, rest.length);
// return res;
// }
// }
// return new int[0];
// }
// }
// Accepted solution for LeetCode #3533: Concatenated Divisibility
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #3533: Concatenated Divisibility
// class Solution {
// public int[] concatenatedDivisibility(int[] nums, int k) {
// final int n = nums.length;
// int[] lengths = new int[n];
// int[] pows = new int[n];
//
// Arrays.sort(nums);
//
// for (int i = 0; i < n; ++i) {
// lengths[i] = String.valueOf(nums[i]).length();
// pows[i] = (int) Math.pow(10, lengths[i]) % k;
// }
//
// Integer[][] mem = new Integer[1 << n][k];
// return dp(nums, pows, mem, k, 0, 0) ? reconstruct(nums, pows, mem, k, 0, 0) : new int[0];
// }
//
// // Returns true if there is a way to form a number divisible by `k` using the
// // numbers in `nums`, where nums[i] is used iff `mask & (1 << i)`.
// private boolean dp(int[] nums, int[] pows, Integer[][] mem, int k, int mask, int mod) {
// if (mem[mask][mod] != null)
// return mem[mask][mod] == 1;
// if (mask == (1 << nums.length) - 1)
// return (mem[mask][mod] = mod == 0 ? 1 : 0) == 1;
// for (int i = 0; i < nums.length; ++i)
// if ((mask >> i & 1) == 0) {
// final int newMod = (mod * pows[i] + nums[i]) % k;
// if (dp(nums, pows, mem, k, mask | 1 << i, newMod))
// return (mem[mask][mod] = 1) == 1;
// }
// return (mem[mask][mod] = 0) == 1;
// }
//
// // Reconstructs the numbers that form a number divisible by `k` using the
// // numbers in `nums`, where nums[i] is used iff `mask & (1 << i)`.
// private int[] reconstruct(int[] nums, int[] pows, Integer[][] mem, int k, int mask, int mod) {
// for (int i = 0; i < nums.length; ++i)
// if ((mask >> i & 1) == 0) {
// final int newMod = (mod * pows[i] + nums[i]) % k;
// if (dp(nums, pows, mem, k, mask | 1 << i, newMod)) {
// int[] first = new int[] {nums[i]};
// int[] rest = reconstruct(nums, pows, mem, k, mask | 1 << i, newMod);
// int[] res = new int[first.length + rest.length];
// System.arraycopy(first, 0, res, 0, first.length);
// System.arraycopy(rest, 0, res, first.length, rest.length);
// return res;
// }
// }
// return new int[0];
// }
// }
Use this to step through a reusable interview workflow for this problem.
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.
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.
Review these before coding to avoid predictable interview regressions.
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.
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.