Number of Beautiful Pairs - Problem
You are given a 0-indexed integer array nums. Your task is to find all beautiful pairs of indices in this array.
A pair of indices (i, j) where 0 โค i < j < nums.length is considered beautiful if:
- The first digit of
nums[i]and the last digit ofnums[j]are coprime
Two integers are coprime if their greatest common divisor (GCD) equals 1. In other words, they share no common factors other than 1.
Example: The first digit of 123 is 1, and the last digit of 456 is 6. Since gcd(1, 6) = 1, they are coprime.
Return the total number of beautiful pairs in the array.
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [2,5,1,4]
โบ
Output:
5
๐ก Note:
Beautiful pairs: (0,1), (0,2), (0,3), (1,2), (2,3). First digits: [2,5,1,4], Last digits: [2,5,1,4]. All adjacent pairs have coprime digits except none - all pairs work since gcd of different single digits except (2,4) and (5,5) cases.
example_2.py โ With Multi-digit Numbers
$
Input:
nums = [11,21,12]
โบ
Output:
2
๐ก Note:
Beautiful pairs: (0,1) and (0,2). For (0,1): first digit of 11 is 1, last digit of 21 is 1, gcd(1,1)=1. For (0,2): first digit of 11 is 1, last digit of 12 is 2, gcd(1,2)=1. For (1,2): first digit of 21 is 2, last digit of 12 is 2, gcd(2,2)=2โ 1.
example_3.py โ Edge Case
$
Input:
nums = [31,25,72,40,51]
โบ
Output:
7
๐ก Note:
Check all pairs where first digit of nums[i] and last digit of nums[j] are coprime. First digits: [3,2,7,4,5], Last digits: [1,5,2,0,1]. Count pairs with gcd=1.
Constraints
- 2 โค nums.length โค 100
- 1 โค nums[i] โค 9999
- All array elements are positive integers
- First digit is never 0 (since numbers are positive)
Visualization
Tap to expand
Understanding the Visualization
1
Extract Digits
Get first digit of each number and last digit of each number
2
Check Coprimality
For each pair (i,j) where i<j, check if gcd(first[i], last[j]) = 1
3
Count Valid Pairs
Count all pairs that satisfy the coprime condition
4
Optimization
Use frequency counting to avoid checking each pair individually
Key Takeaway
๐ฏ Key Insight: The optimal solution leverages the fact that there are only 90 possible (first_digit, last_digit) combinations. By counting digit frequencies, we can calculate beautiful pairs mathematically in O(n) time instead of checking every pair individually.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code