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.

Example: For nums = [232, 124, 456] and k = 4, the permutation [124, 232, 456] creates the number 124232456, which we need to check if it's divisible by 4.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [232, 124, 456], k = 4
โ€บ Output: [124, 232, 456]
๐Ÿ’ก Note: The concatenation '124232456' is divisible by 4. This is the lexicographically smallest valid permutation.
example_2.py โ€” No Solution
$ Input: nums = [11, 13, 17], k = 7
โ€บ Output: []
๐Ÿ’ก Note: No permutation of these numbers creates a concatenation divisible by 7, so we return an empty array.
example_3.py โ€” Single Element
$ Input: nums = [1], k = 1
โ€บ Output: [1]
๐Ÿ’ก Note: Single element case - the number 1 is divisible by 1, so we return [1].

Visualization

Tap to expand
Concatenated Divisibility Visualization232124456Available NumbersArrangement 1:232124456= 232124456Not รท 4Arrangement 2:124232456= 124232456โœ“ รท 4Lexicographically Smallest:[124, 232, 456]๐Ÿ”‘ Key: Use modular arithmetic to avoid integer overflow
Understanding the Visualization
1
Problem Setup
We have number tiles [232, 124, 456] and need divisibility by k=4
2
Try Arrangements
Test different arrangements: 232124456, 124232456, etc.
3
Check Divisibility
Use modular arithmetic to check if concatenated result is divisible by k
4
Find Smallest
Among valid arrangements, return the lexicographically smallest
Key Takeaway
๐ŸŽฏ Key Insight: Use dynamic programming with bitmasks to efficiently explore permutations while using modular arithmetic to avoid integer overflow when checking divisibility.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n ร— 2^n ร— k)

n numbers, 2^n possible masks, k possible remainders

n
2n
โš  Quadratic Growth
Space Complexity
O(2^n ร— k)

DP table storing states for each mask and remainder combination

n
2n
โš  Quadratic Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 8
  • 1 โ‰ค nums[i] โ‰ค 108
  • 1 โ‰ค k โ‰ค 400
  • All integers in nums are unique
Asked in
Google 25 Amazon 18 Meta 15 Microsoft 12
28.4K Views
Medium Frequency
~25 min Avg. Time
847 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