- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 46 lines of Java from the credited upstream file 3490.java.
- The implementation visibly relies on hash lookup, ordered lookup.
- 1 loop block detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int beautifulNumbers(int l, int r) {3 return count(String.valueOf(r), 0, true, true,4 false, 0, 1, new HashMap<>()) -5 count(String.valueOf(l - 1), 0, true, true,6 false, 0, 1, new HashMap<>());7 }8 9 private int count(final String s, int i, boolean tight, boolean isLeadingZero, boolean hasZero,10 int sum, int prod, Map<String, Integer> mem) {11 if (i == s.length()) {12 if (isLeadingZero)13 return 0;14 return (hasZero || prod % sum == 0) ? 1 : 0;15 }16 final String key = hash(i, tight, isLeadingZero, hasZero, sum, prod);17 if (!isLeadingZero && hasZero && !tight) {18 final int val = (int) Math.pow(10, s.length() - i);19 mem.put(key, val);20 return val;21 }22 if (mem.containsKey(key))23 return mem.get(key);24 25 int res = 0;26 final int maxDigit = tight ? s.charAt(i) - '0' : 9;27 28 for (int d = 0; d <= maxDigit; ++d) {29 final boolean nextTight = tight && (d == maxDigit);30 final boolean nextIsLeadingZero = isLeadingZero && d == 0;31 final boolean nextHasZero = !nextIsLeadingZero && d == 0;32 final int nextProd = nextIsLeadingZero ? 1 : prod * d;33 res += count(s, i + 1, nextTight, nextIsLeadingZero, nextHasZero, sum + d, nextProd, mem);34 }35 36 mem.put(key, res);37 return res;38 }39 40 private String hash(int i, boolean tight, boolean isLeadingZero, boolean hasZero, int sum,41 int prod) {42 return i + "_" + (tight ? "1" : "0") + "_" + (isLeadingZero ? "1" : "0") + "_" +43 (hasZero ? "1" : "0") + "_" + sum + "_" + prod;44 }45}46