Start learning free

LESSON 469 OF 671 · STACK

Create Maximum Number in JavaScript (Time Complexity: O((m+n)^3))

Practice O(n) Read the full explanation

You get two arrays of digits, nums1 and nums2. Each digit is from 0 to 9. You also get a number k.

Pick k digits in total from the two lists. Line them up to make the largest possible k-digit number. Return its digits as an array.

Digits from the same list must keep their order from that list. Apart from that, digits from the two lists can mix in any way.

 

Example 1:

Input: nums1 = [5, 2, 8], nums2 = [7, 1, 6, 3], k = 4
Output: [8, 7, 6, 3]
Explanation: Take the 8 from nums1.
Then take 7, 6 and 3 from nums2, in their order.

Example 2:

Input: nums1 = [4, 9], nums2 = [4, 1, 5], k = 5
Output: [4, 9, 4, 1, 5]
Explanation: All five digits are used.
Both lists start with 4.
Taking the 4 of nums1 first lets its 9 come second.
49415 is larger than 44915.

Example 3:

Input: nums1 = [1, 1], nums2 = [3, 0, 2], k = 2
Output: [3, 2]
Explanation: Both digits come from nums2.
Its 0 is skipped.

 

Constraints:

  • nums1 and nums2 each have 1 to 30 digits.
  • k is from 1 to the number of digits in both lists together.
STEP 1 OF 27
    Ctrl + Enter to check

    JAVASCRIPT · STACK

    Create Maximum Number in JavaScript, explained

    Understanding the Problem

    The core challenge of this problem is to create the maximum number of length k by selecting digits from two arrays while maintaining the relative order of digits from each array. This problem is significant in scenarios where we need to merge sorted lists or arrays while maintaining the order and maximizing the resultant value.

    Potential pitfalls include not maintaining the relative order of digits from the same array and not considering all possible combinations of digits from both arrays.

    Approach

    To solve this problem, we need to consider the following steps:

    1. Generate all possible subarrays of different lengths from both arrays.
    2. Merge these subarrays to form the maximum number of length k.
    3. Compare and select the maximum number from all possible combinations.

    Let's start with a naive solution and then optimize it.

    Naive Solution

    The naive solution involves generating all possible subarrays of different lengths from both arrays and then merging them to form the maximum number. This approach is not optimal due to its high time complexity.

    Optimized Solution

    We can optimize the solution by using a greedy approach to generate the maximum subarray of a given length from an array. Then, we merge these subarrays to form the maximum number of length k.

    Algorithm

    Here is a step-by-step breakdown of the optimized algorithm:

    1. Define a function to generate the maximum subarray of a given length from an array.
    2. Define a function to merge two subarrays to form the maximum number while maintaining the relative order.
    3. Iterate through all possible lengths of subarrays from both arrays and use the above functions to generate and merge subarrays.
    4. Compare and select the maximum number from all possible combinations.

    Code Implementation

    /**
     * Function to generate the maximum subarray of a given length from an array
     * @param {number[]} nums - The input array
     * @param {number} k - The length of the subarray
     * @return {number[]} - The maximum subarray of length k
     */
    function maxSubArray(nums, k) {
        const stack = [];
        let drop = nums.length - k;
        for (let num of nums) {
            while (drop && stack.length && stack[stack.length - 1] < num) {
                stack.pop();
                drop--;
            }
            stack.push(num);
        }
        return stack.slice(0, k);
    }
    
    /**
     * Function to merge two subarrays to form the maximum number
     * @param {number[]} nums1 - The first subarray
     * @param {number[]} nums2 - The second subarray
     * @return {number[]} - The merged maximum number
     */
    function merge(nums1, nums2) {
        const result = [];
        while (nums1.length || nums2.length) {
            if (nums1 > nums2) {
                result.push(nums1.shift());
            } else {
                result.push(nums2.shift());
            }
        }
        return result;
    }
    
    /**
     * Main function to create the maximum number of length k from two arrays
     * @param {number[]} nums1 - The first input array
     * @param {number[]} nums2 - The second input array
     * @param {number} k - The length of the maximum number
     * @return {number[]} - The maximum number of length k
     */
    function maxNumber(nums1, nums2, k) {
        let max = [];
        for (let i = Math.max(0, k - nums2.length); i <= Math.min(k, nums1.length); i++) {
            const candidate = merge(maxSubArray(nums1, i), maxSubArray(nums2, k - i));
            if (candidate > max) {
                max = candidate;
            }
        }
        return max;
    }
    
    // Example usage:
    console.log(maxNumber([3, 4, 6, 5], [9, 1, 2, 5, 8, 3], 5)); // Output: [9, 8, 6, 5, 3]
    console.log(maxNumber([6, 7], [6, 0, 4], 5)); // Output: [6, 7, 6, 0, 4]
    console.log(maxNumber([3, 9], [8, 9], 3)); // Output: [9, 8, 9]
    

    Complexity Analysis

    The time complexity of the optimized solution is O((m+n)^3) due to the nested loops and comparisons. The space complexity is O(k) for storing the result.

    Edge Cases

    Potential edge cases include:

    • Arrays with all identical elements.
    • Arrays with only one element.
    • Arrays where k is equal to the sum of the lengths of both arrays.

    Each algorithm handles these edge cases by ensuring the relative order of digits and considering all possible combinations.

    Testing

    To test the solution comprehensively, include a variety of test cases:

    • Simple cases with small arrays.
    • Complex cases with larger arrays and different values of k.
    • Edge cases as mentioned above.

    Use testing frameworks like Jest or Mocha for automated testing.

    Thinking and Problem-Solving Tips

    When approaching such problems, consider the following tips:

    • Break down the problem into smaller subproblems.
    • Think about the constraints and how they affect the solution.
    • Use a greedy approach to maximize the result.
    • Practice similar problems to improve problem-solving skills.

    Conclusion

    In this blog post, we discussed how to create the maximum number of length k from two arrays while maintaining the relative order of digits. We explored a naive solution and an optimized solution, provided a detailed algorithm, and analyzed the complexity. Understanding and solving such problems is crucial for improving problem-solving skills and preparing for coding interviews.

    Additional Resources

    For further reading and practice, consider the following resources:

    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free