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.
You are given two integer arrays nums1 and nums2 of lengths m and n respectively. nums1 and nums2 represent the digits of two numbers. You are also given an integer k.
Create the maximum number of length k <= m + n from digits of the two numbers. The relative order of the digits from the same array must be preserved.
Return an array of the k digits representing the answer.
Example 1:
Input: nums1 = [3,4,6,5], nums2 = [9,1,2,5,8,3], k = 5 Output: [9,8,6,5,3]
Example 2:
Input: nums1 = [6,7], nums2 = [6,0,4], k = 5 Output: [6,7,6,0,4]
Example 3:
Input: nums1 = [3,9], nums2 = [8,9], k = 3 Output: [9,8,9]
Constraints:
m == nums1.lengthn == nums2.length1 <= m, n <= 5000 <= nums1[i], nums2[i] <= 91 <= k <= m + nnums1 and nums2 do not have leading zeros.Problem summary: You are given two integer arrays nums1 and nums2 of lengths m and n respectively. nums1 and nums2 represent the digits of two numbers. You are also given an integer k. Create the maximum number of length k <= m + n from digits of the two numbers. The relative order of the digits from the same array must be preserved. Return an array of the k digits representing the answer.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Two Pointers · Stack · Greedy
[3,4,6,5] [9,1,2,5,8,3] 5
[6,7] [6,0,4] 5
[3,9] [8,9] 3
remove-k-digits)maximum-swap)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #321: Create Maximum Number
class Solution {
public int[] maxNumber(int[] nums1, int[] nums2, int k) {
int m = nums1.length, n = nums2.length;
int l = Math.max(0, k - n), r = Math.min(k, m);
int[] ans = new int[k];
for (int x = l; x <= r; ++x) {
int[] arr1 = f(nums1, x);
int[] arr2 = f(nums2, k - x);
int[] arr = merge(arr1, arr2);
if (compare(arr, ans, 0, 0)) {
ans = arr;
}
}
return ans;
}
private int[] f(int[] nums, int k) {
int n = nums.length;
int[] stk = new int[k];
int top = -1;
int remain = n - k;
for (int x : nums) {
while (top >= 0 && stk[top] < x && remain > 0) {
--top;
--remain;
}
if (top + 1 < k) {
stk[++top] = x;
} else {
--remain;
}
}
return stk;
}
private int[] merge(int[] nums1, int[] nums2) {
int m = nums1.length, n = nums2.length;
int i = 0, j = 0;
int[] ans = new int[m + n];
for (int k = 0; k < m + n; ++k) {
if (compare(nums1, nums2, i, j)) {
ans[k] = nums1[i++];
} else {
ans[k] = nums2[j++];
}
}
return ans;
}
private boolean compare(int[] nums1, int[] nums2, int i, int j) {
if (i >= nums1.length) {
return false;
}
if (j >= nums2.length) {
return true;
}
if (nums1[i] > nums2[j]) {
return true;
}
if (nums1[i] < nums2[j]) {
return false;
}
return compare(nums1, nums2, i + 1, j + 1);
}
}
// Accepted solution for LeetCode #321: Create Maximum Number
func maxNumber(nums1 []int, nums2 []int, k int) []int {
m, n := len(nums1), len(nums2)
l, r := max(0, k-n), min(k, m)
f := func(nums []int, k int) []int {
n := len(nums)
stk := make([]int, k)
top := -1
remain := n - k
for _, x := range nums {
for top >= 0 && stk[top] < x && remain > 0 {
top--
remain--
}
if top+1 < k {
top++
stk[top] = x
} else {
remain--
}
}
return stk
}
var compare func(nums1, nums2 []int, i, j int) bool
compare = func(nums1, nums2 []int, i, j int) bool {
if i >= len(nums1) {
return false
}
if j >= len(nums2) {
return true
}
if nums1[i] > nums2[j] {
return true
}
if nums1[i] < nums2[j] {
return false
}
return compare(nums1, nums2, i+1, j+1)
}
merge := func(nums1, nums2 []int) []int {
m, n := len(nums1), len(nums2)
ans := make([]int, m+n)
i, j := 0, 0
for k := range ans {
if compare(nums1, nums2, i, j) {
ans[k] = nums1[i]
i++
} else {
ans[k] = nums2[j]
j++
}
}
return ans
}
ans := make([]int, k)
for x := l; x <= r; x++ {
arr1 := f(nums1, x)
arr2 := f(nums2, k-x)
arr := merge(arr1, arr2)
if compare(arr, ans, 0, 0) {
ans = arr
}
}
return ans
}
# Accepted solution for LeetCode #321: Create Maximum Number
class Solution:
def maxNumber(self, nums1: List[int], nums2: List[int], k: int) -> List[int]:
def f(nums: List[int], k: int) -> List[int]:
n = len(nums)
stk = [0] * k
top = -1
remain = n - k
for x in nums:
while top >= 0 and stk[top] < x and remain > 0:
top -= 1
remain -= 1
if top + 1 < k:
top += 1
stk[top] = x
else:
remain -= 1
return stk
def compare(nums1: List[int], nums2: List[int], i: int, j: int) -> bool:
if i >= len(nums1):
return False
if j >= len(nums2):
return True
if nums1[i] > nums2[j]:
return True
if nums1[i] < nums2[j]:
return False
return compare(nums1, nums2, i + 1, j + 1)
def merge(nums1: List[int], nums2: List[int]) -> List[int]:
m, n = len(nums1), len(nums2)
i = j = 0
ans = [0] * (m + n)
for k in range(m + n):
if compare(nums1, nums2, i, j):
ans[k] = nums1[i]
i += 1
else:
ans[k] = nums2[j]
j += 1
return ans
m, n = len(nums1), len(nums2)
l, r = max(0, k - n), min(k, m)
ans = [0] * k
for x in range(l, r + 1):
arr1 = f(nums1, x)
arr2 = f(nums2, k - x)
arr = merge(arr1, arr2)
if ans < arr:
ans = arr
return ans
// Accepted solution for LeetCode #321: Create Maximum Number
struct Solution;
impl Solution {
fn max_number(nums1: Vec<i32>, nums2: Vec<i32>, k: i32) -> Vec<i32> {
let n1 = nums1.len();
let n2 = nums2.len();
let k = k as usize;
let mut max_merged: Option<Vec<i32>> = None;
for size1 in 0..=k.min(n1) {
let size2 = k - size1;
if size2 > n2 {
continue;
}
let max1 = Self::max_one(&nums1, size1);
let max2 = Self::max_one(&nums2, size2);
let max3 = Self::max_merge(max1, max2);
if let Some(max) = max_merged {
if max < max3 {
max_merged = Some(max3);
} else {
max_merged = Some(max);
}
} else {
max_merged = Some(max3);
}
}
max_merged.unwrap()
}
fn max_one(nums: &[i32], k: usize) -> Vec<i32> {
let mut stack = vec![];
let n = nums.len();
for i in 0..n {
let right = n - i;
while let Some(&top) = stack.last() {
if top < nums[i] && stack.len() + right > k {
stack.pop();
} else {
break;
}
}
stack.push(nums[i]);
}
while stack.len() > k {
stack.pop();
}
stack
}
fn max_merge(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
let mut res = vec![];
let mut i = 0;
let mut j = 0;
loop {
if i < nums1.len() && j < nums2.len() {
if Self::greater(&nums1, &nums2, i, j) {
res.push(nums1[i]);
i += 1;
} else {
res.push(nums2[j]);
j += 1;
}
continue;
}
if i < nums1.len() {
res.push(nums1[i]);
i += 1;
continue;
}
if j < nums2.len() {
res.push(nums2[j]);
j += 1;
continue;
}
break;
}
res
}
fn greater(nums1: &[i32], nums2: &[i32], mut i: usize, mut j: usize) -> bool {
while i < nums1.len() && j < nums2.len() && nums1[i] == nums2[j] {
i += 1;
j += 1;
}
j == nums2.len() || (i < nums1.len() && nums1[i] > nums2[j])
}
}
#[test]
fn test() {
let nums1 = vec![3, 4, 6, 5];
let nums2 = vec![9, 1, 2, 5, 8, 3];
let k = 5;
let res = vec![9, 8, 6, 5, 3];
assert_eq!(Solution::max_number(nums1, nums2, k), res);
let nums1 = vec![6, 7];
let nums2 = vec![6, 0, 4];
let k = 5;
let res = vec![6, 7, 6, 0, 4];
assert_eq!(Solution::max_number(nums1, nums2, k), res);
let nums1 = vec![3, 9];
let nums2 = vec![8, 9];
let k = 3;
let res = vec![9, 8, 9];
assert_eq!(Solution::max_number(nums1, nums2, k), res);
let nums1 = vec![2, 5, 6, 4, 4, 0];
let nums2 = vec![7, 3, 8, 0, 6, 5, 7, 6, 2];
let k = 15;
let res = vec![7, 3, 8, 2, 5, 6, 4, 4, 0, 6, 5, 7, 6, 2, 0];
assert_eq!(Solution::max_number(nums1, nums2, k), res);
}
// Accepted solution for LeetCode #321: Create Maximum Number
function maxNumber(nums1: number[], nums2: number[], k: number): number[] {
const m = nums1.length;
const n = nums2.length;
const l = Math.max(0, k - n);
const r = Math.min(k, m);
let ans: number[] = Array(k).fill(0);
for (let x = l; x <= r; ++x) {
const arr1 = f(nums1, x);
const arr2 = f(nums2, k - x);
const arr = merge(arr1, arr2);
if (compare(arr, ans, 0, 0)) {
ans = arr;
}
}
return ans;
}
function f(nums: number[], k: number): number[] {
const n = nums.length;
const stk: number[] = Array(k).fill(0);
let top = -1;
let remain = n - k;
for (const x of nums) {
while (top >= 0 && stk[top] < x && remain > 0) {
--top;
--remain;
}
if (top + 1 < k) {
stk[++top] = x;
} else {
--remain;
}
}
return stk;
}
function compare(nums1: number[], nums2: number[], i: number, j: number): boolean {
if (i >= nums1.length) {
return false;
}
if (j >= nums2.length) {
return true;
}
if (nums1[i] > nums2[j]) {
return true;
}
if (nums1[i] < nums2[j]) {
return false;
}
return compare(nums1, nums2, i + 1, j + 1);
}
function merge(nums1: number[], nums2: number[]): number[] {
const m = nums1.length;
const n = nums2.length;
const ans: number[] = Array(m + n).fill(0);
let i = 0;
let j = 0;
for (let k = 0; k < m + n; ++k) {
if (compare(nums1, nums2, i, j)) {
ans[k] = nums1[i++];
} else {
ans[k] = nums2[j++];
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
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: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.
Wrong move: Pushing without popping stale elements invalidates next-greater/next-smaller logic.
Usually fails on: Indices point to blocked elements and outputs shift.
Fix: Pop while invariant is violated before pushing current element.
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.