Partitioning Into Minimum Number Of Deci-Binary Numbers - Problem

A decimal number is called deci-binary if each of its digits is either 0 or 1 without any leading zeros. For example, 101 and 1100 are deci-binary, while 112 and 3001 are not.

Given a string n that represents a positive decimal integer, return the minimum number of positive deci-binary numbers needed so that they sum up to n.

Input & Output

Example 1 — Basic Case
$ Input: n = "32"
Output: 3
💡 Note: We can decompose 32 into three deci-binary numbers: 10 + 11 + 11 = 32. The maximum digit is 3, so we need at least 3 deci-binary numbers.
Example 2 — Single Digit
$ Input: n = "82734"
Output: 8
💡 Note: The maximum digit in 82734 is 8, so we need exactly 8 deci-binary numbers to sum up to this value.
Example 3 — All Same Digits
$ Input: n = "27346209830709182346"
Output: 9
💡 Note: Despite being a very large number, we only need 9 deci-binary numbers because the maximum digit is 9.

Constraints

  • 1 ≤ n.length ≤ 105
  • n consists of only digits
  • n does not contain any leading zeros and represents a positive integer

Visualization

Tap to expand
Minimum Deci-Binary Numbers INPUT String n = "32" 3 digit[0] 2 digit[1] Each digit represents how many 1s needed at that position Deci-Binary Examples: 101, 1100, 11 [OK] 112, 3001 [NOT OK] (digits must be 0 or 1) ALGORITHM STEPS 1 Scan all digits Loop through string n 2 Find max digit max(3, 2) = 3 3 Return max digit Answer = 3 4 Why it works See breakdown below Decomposition of "32": 11 (deci-binary) 11 (deci-binary) 10 (deci-binary) = 32 32 (3 numbers) FINAL RESULT Output: 3 Minimum deci-binary numbers needed = 3 The 3 deci-binary numbers: 11 11 10 + + = 32 Key Insight: The answer is simply the maximum digit in the input string. Each digit d needs d deci-binary 1s at that position. The bottleneck is the largest digit, which determines the minimum count needed. Time Complexity: O(n) | Space Complexity: O(1) TutorialsPoint - Partitioning Into Minimum Number Of Deci-Binary Numbers | Greedy - Maximum Digit Approach
Asked in
Google 15 Amazon 12 Microsoft 8
125.0K Views
Medium Frequency
~10 min Avg. Time
2.8K 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