/**
* Problem: LeetCode 3348 - Smallest Divisible Digit Product II
* Difficulty: Hard
* Language: Java
* Author: CodeByTushu
*/
import java.util.*;
/**
* Problem: LeetCode 3348 - Smallest Divisible Digit Product II
* Difficulty: Hard
* Language: Java
* Author: CodeByTushu
*/
class Solution {
static class Pair<K, V> {
private final K key;
private final V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
}
public String smallestNumber(String num, long t) {
Pair<Map<Integer, Integer>, Boolean> primeCountResult = getPrimeCount(t);
Map<Integer, Integer> primeCount = primeCountResult.getKey();
boolean isDivisible = primeCountResult.getValue();
if (!isDivisible)
return "-1";
Map<Integer, Integer> factorCount = getFactorCount(primeCount);
if (sumValues(factorCount) > num.length())
return construct(factorCount);
Map<Integer, Integer> primeCountPrefix = getPrimeCount(num);
int firstZeroIndex = num.indexOf('0');
if (firstZeroIndex == -1) {
firstZeroIndex = num.length();
if (isSubset(primeCount, primeCountPrefix))
return num;
}
for (int i = num.length() - 1; i >= 0; --i) {
final int d = num.charAt(i) - '0';
// Remove the current digit's factors from primeCountPrefix.
primeCountPrefix = subtract(primeCountPrefix, FACTOR_COUNTS.get(d));
final int spaceAfterThisDigit = num.length() - 1 - i;
if (i > firstZeroIndex)
continue;
for (int biggerDigit = d + 1; biggerDigit < 10; ++biggerDigit) {
// Compute the required factors after replacing with a larger digit.
Map<Integer, Integer> factorsAfterReplacement = getFactorCount(
subtract(subtract(primeCount, primeCountPrefix), FACTOR_COUNTS.get(biggerDigit)));
// Check if the replacement is possible within the available space.
if (sumValues(factorsAfterReplacement) <= spaceAfterThisDigit) {
// Fill extra space with '1', if any, and construct the result.
final int fillOnes = spaceAfterThisDigit - sumValues(factorsAfterReplacement);
return num.substring(0, i) + // Keep the prefix unchanged.
biggerDigit + // Replace the current digit.
"1".repeat(fillOnes) + // Fill remaining space with '1'.
construct(factorsAfterReplacement);
}
}
}
// No solution of the same length exists, so we need to extend the number
// by prepending '1's and adding the required factors.
Map<Integer, Integer> factorsAfterExtension = getFactorCount(primeCount);
return "1".repeat(num.length() + 1 - sumValues(factorsAfterExtension)) +
construct(factorsAfterExtension);
}
private static final Map<Integer, Map<Integer, Integer>> FACTOR_COUNTS = Map.of(
0, Map.of(), 1, Map.of(), 2, Map.of(2, 1), 3, Map.of(3, 1), 4, Map.of(2, 2), 5, Map.of(5, 1),
6, Map.of(2, 1, 3, 1), 7, Map.of(7, 1), 8, Map.of(2, 3), 9, Map.of(3, 2));
// Returns the prime count of t and if t is divisible by 2, 3, 5, 7.
private Pair<Map<Integer, Integer>, Boolean> getPrimeCount(long t) {
Map<Integer, Integer> count = new HashMap<>(Map.of(2, 0, 3, 0, 5, 0, 7, 0));
for (int prime : new int[] {2, 3, 5, 7}) {
while (t % prime == 0) {
t /= prime;
count.put(prime, count.get(prime) + 1);
}
}
return new Pair<>(count, t == 1);
}
// Returns the prime count of `num`.
private Map<Integer, Integer> getPrimeCount(String num) {
Map<Integer, Integer> count = new HashMap<>(Map.of(2, 0, 3, 0, 5, 0, 7, 0));
for (final char c : num.toCharArray()) {
Map<Integer, Integer> digitFactors = FACTOR_COUNTS.get(c - '0');
for (Map.Entry<Integer, Integer> entry : digitFactors.entrySet()) {
final int prime = entry.getKey();
final int freq = entry.getValue();
count.merge(prime, freq, Integer::sum);
}
}
return count;
}
private Map<Integer, Integer> getFactorCount(Map<Integer, Integer> count) {
// 2^3 = 8
final int count8 = count.get(2) / 3;
final int remaining2 = count.get(2) % 3;
// 3^2 = 9
final int count9 = count.get(3) / 2;
int count3 = count.get(3) % 2;
// 2^2 = 4
int count4 = remaining2 / 2;
int count2 = remaining2 % 2;
// Combine 2 and 3 to 6 if both are present
int count6 = 0;
if (count2 == 1 && count3 == 1) {
count2 = 0;
count3 = 0;
count6 = 1;
}
// Combine 3 and 4 to 2 and 6 if both are present
if (count3 == 1 && count4 == 1) {
count2 = 1;
count6 = 1;
count3 = 0;
count4 = 0;
}
return Map.of(2, count2, 3, count3, 4, count4, 5, count.get(5), 6, count6, 7, count.get(7), 8,
count8, 9, count9);
}
private String construct(Map<Integer, Integer> factors) {
StringBuilder sb = new StringBuilder();
for (int digit = 2; digit < 10; ++digit)
sb.append(String.valueOf(digit).repeat(factors.get(digit)));
return sb.toString();
}
// Returns true if a is a subset of b.
private boolean isSubset(Map<Integer, Integer> a, Map<Integer, Integer> b) {
for (Map.Entry<Integer, Integer> entry : a.entrySet())
if (b.get(entry.getKey()) < entry.getValue())
return false;
return true;
}
// Returns a - b.
private Map<Integer, Integer> subtract(Map<Integer, Integer> a, Map<Integer, Integer> b) {
Map<Integer, Integer> res = new HashMap<>(a);
for (Map.Entry<Integer, Integer> entry : b.entrySet()) {
final int key = entry.getKey();
final int value = entry.getValue();
res.put(key, Math.max(0, res.get(key) - value));
}
return res;
}
// Returns the sum of the values in `count`.
private int sumValues(Map<Integer, Integer> count) {
return count.values().stream().mapToInt(Integer::intValue).sum();
}
}
"""
Problem: LeetCode 3348 - Smallest Divisible Digit Product II
Difficulty: Hard
Language: Python
Author: CodeByTushu
"""
from typing import Dict
class Solution:
FACTOR_COUNTS = {
0: {},
1: {},
2: {2: 1},
3: {3: 1},
4: {2: 2},
5: {5: 1},
6: {2: 1, 3: 1},
7: {7: 1},
8: {2: 3},
9: {3: 2}
}
def smallestNumber(self, num: str, t: int) -> str:
prime_count = {2: 0, 3: 0, 5: 0, 7: 0}
for p in [2, 3, 5, 7]:
while t % p == 0:
prime_count[p] += 1
t //= p
if t != 1:
return "-1"
def get_factor_count(count: Dict[int, int]) -> Dict[int, int]:
c2 = max(0, count.get(2, 0))
c3 = max(0, count.get(3, 0))
c5 = max(0, count.get(5, 0))
c7 = max(0, count.get(7, 0))
count8 = c2 // 3
rem2 = c2 % 3
count9 = c3 // 2
count3 = c3 % 2
count4 = rem2 // 2
count2 = rem2 % 2
count6 = 0
if count2 == 1 and count3 == 1:
count2 = 0
count3 = 0
count6 = 1
if count3 == 1 and count4 == 1:
count2 = 1
count6 = 1
count3 = 0
count4 = 0
return {
2: count2,
3: count3,
4: count4,
5: c5,
6: count6,
7: c7,
8: count8,
9: count9
}
def construct(factors: Dict[int, int]) -> str:
res = []
for d in range(2, 10):
cnt = factors.get(d, 0)
if cnt > 0:
res.append(str(d) * cnt)
return "".join(res)
def subtract(a: Dict[int, int], b: Dict[int, int]) -> Dict[int, int]:
res = dict(a)
for k, v in b.items():
res[k] = max(0, res.get(k, 0) - v)
return res
factor_count = get_factor_count(prime_count)
min_digits = sum(factor_count.values())
if min_digits > len(num):
return construct(factor_count)
prime_count_prefix = {2: 0, 3: 0, 5: 0, 7: 0}
for ch in num:
d = int(ch)
for p, cnt in self.FACTOR_COUNTS[d].items():
prime_count_prefix[p] += cnt
first_zero_index = num.find('0')
if first_zero_index == -1:
first_zero_index = len(num)
if all(prime_count_prefix[p] >= prime_count[p] for p in [2, 3, 5, 7]):
return num
cur_prefix = dict(prime_count_prefix)
n = len(num)
for i in range(n - 1, -1, -1):
d = int(num[i])
cur_prefix = subtract(cur_prefix, self.FACTOR_COUNTS[d])
space_after = n - 1 - i
if i > first_zero_index:
continue
for bigger in range(d + 1, 10):
rem_needed = subtract(subtract(prime_count, cur_prefix), self.FACTOR_COUNTS[bigger])
factors_after = get_factor_count(rem_needed)
sum_after = sum(factors_after.values())
if sum_after <= space_after:
fill_ones = space_after - sum_after
return (
num[:i] +
str(bigger) +
("1" * fill_ones) +
construct(factors_after)
)
factors_after_ext = get_factor_count(prime_count)
fill_ones = n + 1 - sum(factors_after_ext.values())
return ("1" * fill_ones) + construct(factors_after_ext)
/**
* Problem: LeetCode 3348 - Smallest Divisible Digit Product II
* Difficulty: Hard
* Language: C++
* Author: CodeByTushu
*/
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Problem: LeetCode 3348 - Smallest Divisible Digit Product II
* Difficulty: Hard
* Language: C++
* Author: CodeByTushu
*/
class Solution {
struct FactorCounts {
int c2 = 0, c3 = 0, c4 = 0, c5 = 0, c6 = 0, c7 = 0, c8 = 0, c9 = 0;
int total() const {
return c2 + c3 + c4 + c5 + c6 + c7 + c8 + c9;
}
string construct() const {
string res = "";
res.append(c2, '2');
res.append(c3, '3');
res.append(c4, '4');
res.append(c5, '5');
res.append(c6, '6');
res.append(c7, '7');
res.append(c8, '8');
res.append(c9, '9');
return res;
}
};
FactorCounts getFactorCount(int c2, int c3, int c5, int c7) {
c2 = max(0, c2);
c3 = max(0, c3);
c5 = max(0, c5);
c7 = max(0, c7);
int count8 = c2 / 3;
int rem2 = c2 % 3;
int count9 = c3 / 2;
int count3 = c3 % 2;
int count4 = rem2 / 2;
int count2 = rem2 % 2;
int count6 = 0;
if (count2 == 1 && count3 == 1) {
count2 = 0;
count3 = 0;
count6 = 1;
}
if (count3 == 1 && count4 == 1) {
count2 = 1;
count6 = 1;
count3 = 0;
count4 = 0;
}
return {count2, count3, count4, c5, count6, c7, count8, count9};
}
public:
string smallestNumber(string num, long long t) {
const int FACTOR_2[10] = {0, 0, 1, 0, 2, 0, 1, 0, 3, 0};
const int FACTOR_3[10] = {0, 0, 0, 1, 0, 0, 1, 0, 0, 2};
const int FACTOR_5[10] = {0, 0, 0, 0, 0, 1, 0, 0, 0, 0};
const int FACTOR_7[10] = {0, 0, 0, 0, 0, 0, 0, 1, 0, 0};
int req2 = 0, req3 = 0, req5 = 0, req7 = 0;
while (t % 2 == 0) { req2++; t /= 2; }
while (t % 3 == 0) { req3++; t /= 3; }
while (t % 5 == 0) { req5++; t /= 5; }
while (t % 7 == 0) { req7++; t /= 7; }
if (t > 1) return "-1";
FactorCounts fc = getFactorCount(req2, req3, req5, req7);
if (fc.total() > (int)num.length()) {
return fc.construct();
}
int cur2 = 0, cur3 = 0, cur5 = 0, cur7 = 0;
int firstZeroIndex = -1;
for (int i = 0; i < (int)num.length(); i++) {
int d = num[i] - '0';
if (d == 0 && firstZeroIndex == -1) {
firstZeroIndex = i;
}
cur2 += FACTOR_2[d];
cur3 += FACTOR_3[d];
cur5 += FACTOR_5[d];
cur7 += FACTOR_7[d];
}
if (firstZeroIndex == -1) {
firstZeroIndex = num.length();
if (cur2 >= req2 && cur3 >= req3 && cur5 >= req5 && cur7 >= req7) {
return num;
}
}
int n = num.length();
for (int i = n - 1; i >= 0; --i) {
int d = num[i] - '0';
cur2 -= FACTOR_2[d];
cur3 -= FACTOR_3[d];
cur5 -= FACTOR_5[d];
cur7 -= FACTOR_7[d];
if (i > firstZeroIndex) continue;
int spaceAfter = n - 1 - i;
for (int bigger = d + 1; bigger <= 9; ++bigger) {
int rem2 = req2 - cur2 - FACTOR_2[bigger];
int rem3 = req3 - cur3 - FACTOR_3[bigger];
int rem5 = req5 - cur5 - FACTOR_5[bigger];
int rem7 = req7 - cur7 - FACTOR_7[bigger];
FactorCounts needed = getFactorCount(rem2, rem3, rem5, rem7);
if (needed.total() <= spaceAfter) {
int fillOnes = spaceAfter - needed.total();
string res = num.substr(0, i);
res += to_string(bigger);
res.append(fillOnes, '1');
res += needed.construct();
return res;
}
}
}
FactorCounts ext = getFactorCount(req2, req3, req5, req7);
int fillOnes = n + 1 - ext.total();
string res = "";
res.append(fillOnes, '1');
res += ext.construct();
return res;
}
};
/**
* Problem: LeetCode 3348 - Smallest Divisible Digit Product II
* Difficulty: Hard
* Language: JavaScript
* Author: CodeByTushu
*/
var smallestNumber = function(num, t) {
let target = BigInt(t);
const primes = [2n, 3n, 5n, 7n];
const primeCount = { 2: 0, 3: 0, 5: 0, 7: 0 };
for (const p of primes) {
while (target % p === 0n) {
primeCount[Number(p)]++;
target /= p;
}
}
if (target !== 1n) return "-1";
const FACTOR_COUNTS = {
0: {},
1: {},
2: { 2: 1 },
3: { 3: 1 },
4: { 2: 2 },
5: { 5: 1 },
6: { 2: 1, 3: 1 },
7: { 7: 1 },
8: { 2: 3 },
9: { 3: 2 }
};
function getFactorCount(count) {
const c2 = count[2] || 0;
const c3 = count[3] || 0;
const c5 = count[5] || 0;
const c7 = count[7] || 0;
const count8 = Math.floor(c2 / 3);
const rem2 = c2 % 3;
const count9 = Math.floor(c3 / 2);
let count3 = c3 % 2;
let count4 = Math.floor(rem2 / 2);
let count2 = rem2 % 2;
let count6 = 0;
if (count2 === 1 && count3 === 1) {
count2 = 0;
count3 = 0;
count6 = 1;
}
if (count3 === 1 && count4 === 1) {
count2 = 1;
count6 = 1;
count3 = 0;
count4 = 0;
}
return {
2: count2,
3: count3,
4: count4,
5: c5,
6: count6,
7: c7,
8: count8,
9: count9
};
}
function sumValues(factors) {
let sum = 0;
for (let d = 2; d <= 9; d++) sum += factors[d] || 0;
return sum;
}
function construct(factors) {
let res = "";
for (let d = 2; d <= 9; d++) {
if (factors[d]) res += String(d).repeat(factors[d]);
}
return res;
}
function subtract(a, b) {
const res = { ...a };
for (const [k, v] of Object.entries(b)) {
res[k] = Math.max(0, (res[k] || 0) - v);
}
return res;
}
function isSubset(req, cur) {
for (const p of [2, 3, 5, 7]) {
if ((cur[p] || 0) < (req[p] || 0)) return false;
}
return true;
}
const factorCount = getFactorCount(primeCount);
const minDigits = sumValues(factorCount);
if (minDigits > num.length) {
return construct(factorCount);
}
const primeCountPrefix = { 2: 0, 3: 0, 5: 0, 7: 0 };
for (let i = 0; i < num.length; i++) {
const d = Number(num[i]);
const fc = FACTOR_COUNTS[d];
for (const [p, cnt] of Object.entries(fc)) {
primeCountPrefix[p] += cnt;
}
}
let firstZeroIndex = num.indexOf('0');
if (firstZeroIndex === -1) {
firstZeroIndex = num.length;
if (isSubset(primeCount, primeCountPrefix)) {
return num;
}
}
let curPrefix = { ...primeCountPrefix };
const n = num.length;
for (let i = n - 1; i >= 0; i--) {
const d = Number(num[i]);
curPrefix = subtract(curPrefix, FACTOR_COUNTS[d]);
const spaceAfter = n - 1 - i;
if (i > firstZeroIndex) continue;
for (let bigger = d + 1; bigger <= 9; bigger++) {
const neededAfterPrefix = subtract(primeCount, curPrefix);
const needed = subtract(neededAfterPrefix, FACTOR_COUNTS[bigger]);
const factorsAfter = getFactorCount(needed);
const sumAfter = sumValues(factorsAfter);
if (sumAfter <= spaceAfter) {
const fillOnes = spaceAfter - sumAfter;
return (
num.slice(0, i) +
bigger +
"1".repeat(fillOnes) +
construct(factorsAfter)
);
}
}
}
const factorsAfterExt = getFactorCount(primeCount);
const fillOnes = n + 1 - sumValues(factorsAfterExt);
return "1".repeat(fillOnes) + construct(factorsAfterExt);
};