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: 1
💡 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 INPUT nums array (indices 0-3) 11 i=0 21 i=1 22 i=2 12 i=3 First & Last Digits: 11: first=1, last=1 21: first=2, last=1 22: first=2, last=2 12: first=1, last=2 Coprime: gcd(x,y) == 1 No common divisor > 1 ALGORITHM STEPS 1 Extract Digits Get first digit of nums[i] Get last digit of nums[j] 2 Check All Pairs For each i < j, check if gcd(first[i], last[j])==1 3 Count Beautiful Increment count for each coprime pair All Valid Pairs (i<j): (0,1): gcd(1,1)=1 --> OK (0,2): gcd(1,2)=1 --> OK (0,3): gcd(1,2)=1 --> OK (1,2): gcd(2,2)=2 --> NO (1,3): gcd(2,2)=2 --> NO (2,3): gcd(2,2)=2 --> NO FINAL RESULT Beautiful Pairs Found: Pair (0,1): nums[0]=11, nums[1]=21 first(11)=1, last(21)=1, gcd=1 OK Pair (0,2): nums[0]=11, nums[2]=22 first(11)=1, last(22)=2, gcd=1 OK Pair (0,3): nums[0]=11, nums[3]=12 first(11)=1, last(12)=2, gcd=1 OK OUTPUT 3 Total beautiful pairs Key Insight: To find beautiful pairs, extract the first digit using division (while n>=10, n=n/10) and the last digit using modulo (n%10). Two numbers are coprime when gcd equals 1. Optimal: Use frequency array to count first digits, reducing comparisons significantly. TutorialsPoint - Number of Beautiful Pairs | Optimal Solution
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