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: [1,3,2]
💡 Note: Trying permutations: [1,2,3]→123 (123÷6=20.5, not divisible), [1,3,2]→132 (132÷6=22, 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 [1,3,2] and [3,1,2]. Lexicographically smallest is [1,3,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 - DP Approach INPUT nums array: 1 idx 0 2 idx 1 3 idx 2 Divisor k: 6 Find permutation where concatenation % 6 = 0 Examples: 123, 132, 213... Need lex. smallest valid ALGORITHM STEPS 1 DP State Definition dp[mask][rem] = valid path mask: used elements bitmap 2 Transition Logic new_rem = (old_rem * 10^d + num) % k 3 Lex Order Search Try elements in sorted order at each position 4 Backtrack Solution Reconstruct path when final remainder = 0 DP Table (mask, rem) Try 1: 1-->12-->123=123%6=3 Try 2: 2-->21-->213=213%6=3 Try 3: 2-->21-->213 NO Found: 2-->1-->3=213%6=3 FINAL RESULT Output Permutation: 2 1 3 Verification: "2"+"1"+"3"="213" 213 % 6 = 35*6+3 213 / 6 = 35.5 Lex smallest valid: [2, 1, 3] Key Insight: Use DP with bitmask to track used elements and remainder. State: dp[mask][remainder]. To get lex smallest, try elements in sorted order at each position. New remainder calculation: new_rem = (current_rem * 10^(digits of next num) + next_num) % k TutorialsPoint - Concatenated Divisibility | DP with Bitmask Approach
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