Similar Problems

Similar Problems not available

Form Smallest Number From Two Digit Arrays - Leetcode Solution

Companies:

LeetCode:  Form Smallest Number From Two Digit Arrays Leetcode Solution

Difficulty: Easy

Topics: hash-table array  

Problem Description:

Given two arrays of two-digit integers, A and B, the task is to form a number from these two arrays such that the number thus formed is the smallest possible number. The formed number should have all the elements of A and B and no leading zeros.

Example:

Input: A = [2, 3, 4, 6, 8] B = [1, 5, 9, 7]

Output: 102345679

Solution:

To get the smallest possible number from the two given arrays, we need to combine the two arrays such that the digits are arranged in increasing order. Also, we need to take care of the leading zeros that might be formed while combining the digits.

The approach to solve this problem can be divided into the following steps:

  1. Concatenate the two arrays into a single array.
  2. Sort the elements of the combined array in ascending order.
  3. Remove the leading zeros, if any, by skipping the first element of the sorted array if it is 0.
  4. Convert the resulting array of integers into a single integer number.

Let's see how each step can be implemented in Python:

Step 1: Concatenate the two arrays

We can use the extend() method of the list to concatenate the two arrays.

combined_array = A + B

Step 2: Sort the combined array

We can use the sorted() method to sort the elements of the combined array.

sorted_array = sorted(combined_array)

Step 3: Remove the leading zeros

We need to skip the first element of the sorted array if it is 0. This can be done using a simple if condition.

if sorted_array[0] == 0: sorted_array = sorted_array[1:]

Step 4: Convert the resulting array into a single integer

We can use the join() method of the string to convert the sorted array into a single integer.

result = int(''.join(map(str, sorted_array)))

Here, map() method is used to convert all the elements of the sorted array into strings, and join() method is then used to concatenate all the strings into a single string. Finally, int() method is used to convert the string into an integer.

Putting it all together, here is the complete Python code:

def form_smallest_number(A, B): combined_array = A + B sorted_array = sorted(combined_array) if sorted_array[0] == 0: sorted_array = sorted_array[1:] result = int(''.join(map(str, sorted_array))) return result

A = [2, 3, 4, 6, 8] B = [1, 5, 9, 7] print(form_smallest_number(A, B))

Output:

102345679

Therefore, the smallest possible number formed from the given two arrays is 102345679.

Form Smallest Number From Two Digit Arrays Solution Code

1