Number of Beautiful Pairs — LeetCode 2748 Python Solution
- Problem
- #2748
- Pattern
- Math and Number Theory
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given a 0-indexed integer array nums. A pair of indices i, j where 0 <= i < j < nums.length is called beautiful if the first digit of nums[i] and the last digit of nums[j] are coprime.
Example
- Input
- nums = [2,5,1,4]
- Output
- 5
- Explanation
- There are 5 beautiful pairs in nums:
Python solution
class Solution:
def countBeautifulPairs(self, nums: List[int]) -> int:
cnt = [0] * 10
ans = 0
for x in nums:
for y in range(10):
if cnt[y] and gcd(x % 10, y) == 1:
ans += cnt[y]
cnt[int(str(x)[0])] += 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times (k + \log M)) |
| Space | O(k + \log M) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2748. Number of Beautiful Pairs is filed here because LeetCode tags it Math and Number Theory, which is the vocabulary this hub collects.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2748. Number of Beautiful Pairs?
- LeetCode 2748. Number of Beautiful Pairs is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2748. Number of Beautiful Pairs?
- The Python solution on this page runs in O(n \times (k + \log M)).
- What is the space complexity of LeetCode 2748. Number of Beautiful Pairs?
- The Python solution on this page uses O(k + \log M) auxiliary space.
- What topics does LeetCode 2748. Number of Beautiful Pairs cover?
- LeetCode 2748. Number of Beautiful Pairs is tagged Array, Hash Table, Math, Counting and Number Theory on LeetCode.