Form Smallest Number From Two Digit Arrays — LeetCode 2605 Python Solution
EasyArrayHash TableEnumeration
- Problem
- #2605
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given two arrays of unique digits nums1 and nums2, return the smallest number that contains at least one digit from each array.
Example
- Input
- nums1 = [4,1,3], nums2 = [5,7]
- Output
- 15
- Explanation
- The number 15 contains the digit 1 from nums1 and the digit 5 from nums2. It can be proven that 15 is the smallest number we can have.
Python solution
Python
class Solution:
def minNumber(self, nums1: List[int], nums2: List[int]) -> int:
ans = 100
for a in nums1:
for b in nums2:
if a == b:
ans = min(ans, a)
else:
ans = min(ans, 10 * a + b, 10 * b + a)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(m \times n) |
| Space | O(1), where m and n are the lengths of the arrays nums1 and nums2 auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2605. Form Smallest Number From Two Digit Arrays is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2605. Form Smallest Number From Two Digit Arrays?
- LeetCode 2605. Form Smallest Number From Two Digit Arrays is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2605. Form Smallest Number From Two Digit Arrays?
- The Python solution on this page runs in O(m \times n).
- What is the space complexity of LeetCode 2605. Form Smallest Number From Two Digit Arrays?
- The Python solution on this page uses O(1), where m and n are the lengths of the arrays nums1 and nums2 auxiliary space.
- What topics does LeetCode 2605. Form Smallest Number From Two Digit Arrays cover?
- LeetCode 2605. Form Smallest Number From Two Digit Arrays is tagged Array, Hash Table and Enumeration on LeetCode.