Number of Beautiful Pairs - 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.

Return the total number of beautiful pairs in nums.

Two integers x and y are coprime if there is no integer greater than 1 that divides both of them. In other words, x and y are coprime if gcd(x, y) == 1, where gcd(x, y) is the greatest common divisor of x and y.

Input & Output

Example 1 — Basic Case
$ Input: nums = [11, 21, 22, 12]
Output: 3
💡 Note: Beautiful pairs: (0,1) first=1,last=1 gcd=1; (0,2) first=1,last=2 gcd=1; (0,3) first=1,last=2 gcd=1
Example 2 — No Beautiful Pairs
$ Input: nums = [42, 21]
Output: 0
💡 Note: Only pair (0,1): first=4, last=1, gcd(4,1)=1, so we have 1 beautiful pair
Example 3 — All Beautiful
$ Input: nums = [31, 25, 72, 18]
Output: 5
💡 Note: Most pairs have coprime first and last digits: (0,1),(0,2),(0,3),(1,2),(2,3) are beautiful

Constraints

  • 2 ≤ nums.length ≤ 100
  • 1 ≤ nums[i] ≤ 9999

Visualization

Tap to expand
Number of Beautiful Pairs: GCD of First and Last Digits = 111212212first=1first=2first=2first=1last=1last=1last=2last=2Beautiful pairs: gcd(1,1)=1, gcd(1,2)=1, gcd(1,2)=1Result: 3 beautiful pairs
Understanding the Visualization
1
Input
Array of integers with first and last digits to check
2
Process
For each pair (i,j) where i<j, check if gcd(first[i], last[j]) = 1
3
Output
Count of all beautiful pairs found
Key Takeaway
🎯 Key Insight: A pair is beautiful when the first digit of nums[i] and last digit of nums[j] share no common factors except 1
Asked in
Google 15 Microsoft 12
23.5K Views
Medium Frequency
~15 min Avg. Time
845 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen