Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on array fundamentals.
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.
Example 1:
Input: nums = [2,5,1,4] Output: 5 Explanation: There are 5 beautiful pairs in nums: When i = 0 and j = 1: the first digit of nums[0] is 2, and the last digit of nums[1] is 5. We can confirm that 2 and 5 are coprime, since gcd(2,5) == 1. When i = 0 and j = 2: the first digit of nums[0] is 2, and the last digit of nums[2] is 1. Indeed, gcd(2,1) == 1. When i = 1 and j = 2: the first digit of nums[1] is 5, and the last digit of nums[2] is 1. Indeed, gcd(5,1) == 1. When i = 1 and j = 3: the first digit of nums[1] is 5, and the last digit of nums[3] is 4. Indeed, gcd(5,4) == 1. When i = 2 and j = 3: the first digit of nums[2] is 1, and the last digit of nums[3] is 4. Indeed, gcd(1,4) == 1. Thus, we return 5.
Example 2:
Input: nums = [11,21,12] Output: 2 Explanation: There are 2 beautiful pairs: When i = 0 and j = 1: the first digit of nums[0] is 1, and the last digit of nums[1] is 1. Indeed, gcd(1,1) == 1. When i = 0 and j = 2: the first digit of nums[0] is 1, and the last digit of nums[2] is 2. Indeed, gcd(1,2) == 1. Thus, we return 2.
Constraints:
2 <= nums.length <= 1001 <= nums[i] <= 9999nums[i] % 10 != 0Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Math
[2,5,1,4]
[11,21,12]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2748: Number of Beautiful Pairs
class Solution {
public int countBeautifulPairs(int[] nums) {
int[] cnt = new int[10];
int ans = 0;
for (int x : nums) {
for (int y = 0; y < 10; ++y) {
if (cnt[y] > 0 && gcd(x % 10, y) == 1) {
ans += cnt[y];
}
}
while (x > 9) {
x /= 10;
}
++cnt[x];
}
return ans;
}
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
// Accepted solution for LeetCode #2748: Number of Beautiful Pairs
func countBeautifulPairs(nums []int) (ans int) {
cnt := [10]int{}
for _, x := range nums {
for y := 0; y < 10; y++ {
if cnt[y] > 0 && gcd(x%10, y) == 1 {
ans += cnt[y]
}
}
for x > 9 {
x /= 10
}
cnt[x]++
}
return
}
func gcd(a, b int) int {
if b == 0 {
return a
}
return gcd(b, a%b)
}
# Accepted solution for LeetCode #2748: Number of Beautiful Pairs
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 ans
// Accepted solution for LeetCode #2748: Number of Beautiful Pairs
fn count_beautiful_pairs(nums: Vec<i32>) -> i32 {
use std::collections::HashSet;
fn gcd(a: i32, b: i32) -> i32 {
let mut a = a;
let mut b = b;
loop {
let tmp = a % b;
if tmp == 0 {
return b;
}
a = b;
b = tmp;
}
}
let pairs: Vec<(i32, i32)> = nums
.into_iter()
.map(|n| n.to_string().bytes().collect::<Vec<u8>>())
.map(|bs| ((bs[0] - b'0') as i32, (*bs.last().unwrap() - b'0') as i32))
.collect();
let mut cache = HashSet::new();
let len = pairs.len();
let mut ret = 0;
for i in 0..len {
for j in (i + 1)..len {
if cache.contains(&(pairs[i].0, pairs[j].1)) || gcd(pairs[i].0, pairs[j].1) == 1 {
cache.insert((pairs[i].0, pairs[j].1));
ret += 1;
}
}
}
ret
}
fn main() {
let nums = vec![2, 5, 1, 4];
let ret = count_beautiful_pairs(nums);
println!("ret={ret}");
}
#[test]
fn test_count_beautiful_pairs() {
{
let nums = vec![2, 5, 1, 4];
let ret = count_beautiful_pairs(nums);
assert_eq!(ret, 5);
}
{
let nums = vec![11, 21, 12];
let ret = count_beautiful_pairs(nums);
assert_eq!(ret, 2);
}
{
let nums = vec![31, 25, 72, 79, 74];
let ret = count_beautiful_pairs(nums);
assert_eq!(ret, 7);
}
}
// Accepted solution for LeetCode #2748: Number of Beautiful Pairs
function countBeautifulPairs(nums: number[]): number {
const cnt: number[] = Array(10).fill(0);
let ans = 0;
for (let x of nums) {
for (let y = 0; y < 10; ++y) {
if (cnt[y] > 0 && gcd(x % 10, y) === 1) {
ans += cnt[y];
}
}
while (x > 9) {
x = Math.floor(x / 10);
}
++cnt[x];
}
return ans;
}
function gcd(a: number, b: number): number {
if (b === 0) {
return a;
}
return gcd(b, a % b);
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.