Concatenated Divisibility - Problem

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.

Input & Output

Example 1 — Basic Valid Case
$ Input: nums = [1,2,3], k = 6
Output: [2,1,3]
💡 Note: Trying permutations: [1,2,3]→123 (not divisible), [1,3,2]→132 (not divisible), [2,1,3]→213 (not divisible), [2,3,1]→231 (not divisible), [3,1,2]→312 (312÷6=52, divisible!), [3,2,1]→321 (not divisible). Valid permutations are [3,1,2]. Lexicographically smallest is [3,1,2].
Example 2 — No Valid Solution
$ Input: nums = [1,2,5], k = 6
Output: []
💡 Note: All possible concatenations: 125, 152, 215, 251, 512, 521. None are divisible by 6, so return empty array.
Example 3 — Single Element
$ Input: nums = [12], k = 4
Output: [12]
💡 Note: Only one permutation possible: [12] → 12. Since 12 ÷ 4 = 3, it's divisible, so return [12].

Constraints

  • 1 ≤ nums.length ≤ 12
  • 1 ≤ nums[i] ≤ 109
  • 1 ≤ k ≤ 103

Visualization

Tap to expand
Concatenated Divisibility: Find arrangement divisible by k123Input: nums = [1,2,3], k = 6Try different arrangements:[1,2,3] → 123[1,3,2] → 132[2,1,3] → 213[2,3,1] → 231[3,1,2] → 312[3,2,1] → 321Check divisibility: 123%6≠0, 132%6≠0, 213%6≠0, 231%6≠0, 312%6=0 ✓, 321%6≠0Valid arrangement: [3,1,2] creates 312 which is divisible by 6Result: [3,1,2] (lexicographically smallest valid permutation)
Understanding the Visualization
1
Input
Array [1,2,3] and divisor k=6
2
Process
Try different arrangements and check divisibility
3
Output
Return lexicographically smallest valid permutation
Key Takeaway
🎯 Key Insight: Use DP with bitmask to track remainder modulo k while building permutations, avoiding overflow and reducing complexity from O(n!) to O(n × 2ⁿ × k)
Asked in
Google 15 Microsoft 12 Amazon 8 Meta 6
8.2K Views
Medium Frequency
~35 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen