Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
Given an array of digits digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order. If there is no answer return an empty string.
Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not contain unnecessary leading zeros.
Example 1:
Input: digits = [8,1,9] Output: "981"
Example 2:
Input: digits = [8,6,7,1,0] Output: "8760"
Example 3:
Input: digits = [1] Output: ""
Constraints:
1 <= digits.length <= 1040 <= digits[i] <= 9Problem summary: Given an array of digits digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order. If there is no answer return an empty string. Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not contain unnecessary leading zeros.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Math · Dynamic Programming · Greedy
[8,1,9]
[8,6,7,1,0]
[1]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1363: Largest Multiple of Three
class Solution {
public String largestMultipleOfThree(int[] digits) {
Arrays.sort(digits);
int n = digits.length;
int[][] f = new int[n + 1][3];
final int inf = 1 << 30;
for (var g : f) {
Arrays.fill(g, -inf);
}
f[0][0] = 0;
for (int i = 1; i <= n; ++i) {
for (int j = 0; j < 3; ++j) {
f[i][j] = Math.max(f[i - 1][j], f[i - 1][(j - digits[i - 1] % 3 + 3) % 3] + 1);
}
}
if (f[n][0] <= 0) {
return "";
}
StringBuilder sb = new StringBuilder();
for (int i = n, j = 0; i > 0; --i) {
int k = (j - digits[i - 1] % 3 + 3) % 3;
if (f[i - 1][k] + 1 == f[i][j]) {
sb.append(digits[i - 1]);
j = k;
}
}
int i = 0;
while (i < sb.length() - 1 && sb.charAt(i) == '0') {
++i;
}
return sb.substring(i);
}
}
// Accepted solution for LeetCode #1363: Largest Multiple of Three
func largestMultipleOfThree(digits []int) string {
sort.Ints(digits)
n := len(digits)
const inf = 1 << 30
f := make([][]int, n+1)
for i := range f {
f[i] = make([]int, 3)
for j := range f[i] {
f[i][j] = -inf
}
}
f[0][0] = 0
for i := 1; i <= n; i++ {
for j := 0; j < 3; j++ {
f[i][j] = max(f[i-1][j], f[i-1][(j-digits[i-1]%3+3)%3]+1)
}
}
if f[n][0] <= 0 {
return ""
}
ans := []byte{}
for i, j := n, 0; i > 0; i-- {
k := (j - digits[i-1]%3 + 3) % 3
if f[i][j] == f[i-1][k]+1 {
ans = append(ans, byte('0'+digits[i-1]))
j = k
}
}
i := 0
for i < len(ans)-1 && ans[i] == '0' {
i++
}
return string(ans[i:])
}
# Accepted solution for LeetCode #1363: Largest Multiple of Three
class Solution:
def largestMultipleOfThree(self, digits: List[int]) -> str:
digits.sort()
n = len(digits)
f = [[-inf] * 3 for _ in range(n + 1)]
f[0][0] = 0
for i, x in enumerate(digits, 1):
for j in range(3):
f[i][j] = max(f[i - 1][j], f[i - 1][(j - x % 3 + 3) % 3] + 1)
if f[n][0] <= 0:
return ""
arr = []
j = 0
for i in range(n, 0, -1):
k = (j - digits[i - 1] % 3 + 3) % 3
if f[i - 1][k] + 1 == f[i][j]:
arr.append(digits[i - 1])
j = k
i = 0
while i < len(arr) - 1 and arr[i] == 0:
i += 1
return "".join(map(str, arr[i:]))
// Accepted solution for LeetCode #1363: Largest Multiple of Three
/**
* [1363] Largest Multiple of Three
*
* Given an array of digits digits, return the largest multiple of three that can be formed by concatenating some of the given digits in any order. If there is no answer return an empty string.
* Since the answer may not fit in an integer data type, return the answer as a string. Note that the returning answer must not contain unnecessary leading zeros.
*
* Example 1:
*
* Input: digits = [8,1,9]
* Output: "981"
*
* Example 2:
*
* Input: digits = [8,6,7,1,0]
* Output: "8760"
*
* Example 3:
*
* Input: digits = [1]
* Output: ""
*
*
* Constraints:
*
* 1 <= digits.length <= 10^4
* 0 <= digits[i] <= 9
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/largest-multiple-of-three/
// discuss: https://leetcode.com/problems/largest-multiple-of-three/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
// Credit: https://leetcode.com/problems/largest-multiple-of-three/solutions/3103997/just-a-runnable-solution/
pub fn largest_multiple_of_three(digits: Vec<i32>) -> String {
let mut bucket = [0; 10];
let mut result = Vec::new();
for digit in digits.iter() {
bucket[*digit as usize] += 1;
}
let (mut cnt_g1, mut cnt_g2) = (0_usize, 0_usize);
for i in 0..10 {
if i == 0 || i == 3 || i == 6 || i == 9 {
for _ in 0..bucket[i as usize] {
result.push(i);
}
bucket[i as usize] = 0;
} else if i == 1 || i == 4 || i == 7 {
cnt_g1 += bucket[i as usize];
} else {
cnt_g2 += bucket[i as usize];
}
}
if cnt_g1 % 3 == cnt_g2 % 3 {
let mut fin_res = digits;
fin_res.sort_by(|a, b| b.cmp(a));
if fin_res[0] == 0 {
return String::from("0");
}
return fin_res
.iter()
.map(|a| ((*a + '0' as i32) as u8) as char)
.collect::<String>();
}
if cnt_g1 > 0 && cnt_g1 % 3 == 0 && cnt_g2 % 3 == 2 {
for _ in 0..(cnt_g1 - 1) {
if bucket[7] > 0 {
result.push(7);
bucket[7] -= 1;
} else if bucket[4] > 0 {
result.push(4);
bucket[4] -= 1;
} else if bucket[1] > 0 {
result.push(1);
bucket[1] -= 1;
}
}
for _ in 0..(cnt_g2) {
if bucket[8] > 0 {
result.push(8);
bucket[8] -= 1;
} else if bucket[5] > 0 {
result.push(5);
bucket[5] -= 1;
} else if bucket[2] > 0 {
result.push(2);
bucket[2] -= 1;
}
}
} else if cnt_g2 > 0 && cnt_g2 % 3 == 0 && cnt_g1 % 3 == 2 {
for _ in 0..(cnt_g2 - 1) {
if bucket[8] > 0 {
result.push(8);
bucket[8] -= 1;
} else if bucket[5] > 0 {
result.push(5);
bucket[5] -= 1;
} else if bucket[2] > 0 {
result.push(2);
bucket[2] -= 1;
}
}
for _ in 0..(cnt_g1) {
if bucket[7] > 0 {
result.push(7);
bucket[7] -= 1;
} else if bucket[4] > 0 {
result.push(4);
bucket[4] -= 1;
} else if bucket[1] > 0 {
result.push(1);
bucket[1] -= 1;
}
}
} else {
for _ in 0..(cnt_g1 - cnt_g1 % 3) {
if bucket[7] > 0 {
result.push(7);
bucket[7] -= 1;
} else if bucket[4] > 0 {
result.push(4);
bucket[4] -= 1;
} else if bucket[1] > 0 {
result.push(1);
bucket[1] -= 1;
}
}
cnt_g1 %= 3;
for _ in 0..(cnt_g2 - cnt_g2 % 3) {
if bucket[8] > 0 {
result.push(8);
bucket[8] -= 1;
} else if bucket[5] > 0 {
result.push(5);
bucket[5] -= 1;
} else if bucket[2] > 0 {
result.push(2);
bucket[2] -= 1;
}
}
cnt_g2 %= 3;
if cnt_g1 + cnt_g2 == 3 {
if bucket[7] > 0 {
result.push(7);
bucket[7] -= 1;
} else if bucket[4] > 0 {
result.push(4);
bucket[4] -= 1;
} else if bucket[1] > 0 {
result.push(1);
bucket[1] -= 1;
}
if bucket[8] > 0 {
result.push(8);
bucket[8] -= 1;
} else if bucket[5] > 0 {
result.push(5);
bucket[5] -= 1;
} else if bucket[2] > 0 {
result.push(2);
bucket[2] -= 1;
}
}
}
result.sort_by(|a, b| b.cmp(a));
if let Some(&v) = result.first() {
if v == 0 {
return String::from("0");
}
}
result
.iter()
.map(|a| ((*a + '0' as i32) as u8) as char)
.collect::<String>()
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1363_example_1() {
let digits = vec![8, 1, 9];
let result = "981".to_string();
assert_eq!(Solution::largest_multiple_of_three(digits), result);
}
#[test]
fn test_1363_example_2() {
let digits = vec![8, 6, 7, 1, 0];
let result = "8760".to_string();
assert_eq!(Solution::largest_multiple_of_three(digits), result);
}
#[test]
fn test_1363_example_3() {
let digits = vec![1];
let result = "".to_string();
assert_eq!(Solution::largest_multiple_of_three(digits), result);
}
}
// Accepted solution for LeetCode #1363: Largest Multiple of Three
function largestMultipleOfThree(digits: number[]): string {
digits.sort((a, b) => a - b);
const n = digits.length;
const f: number[][] = new Array(n + 1).fill(0).map(() => new Array(3).fill(-Infinity));
f[0][0] = 0;
for (let i = 1; i <= n; ++i) {
for (let j = 0; j < 3; ++j) {
f[i][j] = Math.max(f[i - 1][j], f[i - 1][(j - (digits[i - 1] % 3) + 3) % 3] + 1);
}
}
if (f[n][0] <= 0) {
return '';
}
const arr: number[] = [];
for (let i = n, j = 0; i; --i) {
const k = (j - (digits[i - 1] % 3) + 3) % 3;
if (f[i - 1][k] + 1 === f[i][j]) {
arr.push(digits[i - 1]);
j = k;
}
}
let i = 0;
while (i < arr.length - 1 && arr[i] === 0) {
++i;
}
return arr.slice(i).join('');
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.