Leetcode 2748. Number of Beautiful Pairs
Given a positive integer array nums
, return the number of pairs (i, j)
(where i < j
) such that the combination of the first digit of nums[i]
and the last digit of nums[j]
form a beautiful pair.
A pair (num1, num2)
is considered beautiful if the sum of the two digits is a prime number.
Input: nums = [12, 34, 56, 78]
Output: 4
Explanation: Pairs are (12, 34), (12, 56), (34, 56), (34, 78). The valid pairs are those with prime sums.
Input: nums = [11, 42, 33, 90]
Output: 2
Explanation: Pairs are (11, 42), (11, 33), (11, 90), (42, 33), (42, 90), (33, 90). The valid pairs are those with prime sums.
nums[i]
and the last digit of nums[j]
.(i, j)
where i < j
and check if they form a beautiful pair.Here’s a sample implementation in Java:
import java.util.ArrayList;
import java.util.List;
public class BeautifulPairs {
private static boolean[] primes;
public static int numberOfBeautifulPairs(int[] nums) {
primes = new boolean[19];
sieveOfEratosthenes(18);
int count = 0;
for (int i = 0; i < nums.length; i++) {
int firstDigit = getFirstDigit(nums[i]);
for (int j = i + 1; j < nums.length; j++) {
int lastDigit = getLastDigit(nums[j]);
if (primes[firstDigit + lastDigit]) {
count++;
}
}
}
return count;
}
private static int getFirstDigit(int num) {
while (num >= 10) num /= 10;
return num;
}
private static int getLastDigit(int num) {
return num % 10;
}
private static void sieveOfEratosthenes(int max) {
primes[2] = true; // Only set 2 directly, as all other indexes default to false
for (int i = 3; i <= max; i++) {
primes[i] = isPrime(i);
}
}
private static boolean isPrime(int num) {
if (num < 2) return false;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return false;
}
return true;
}
public static void main(String[] args) {
int[] nums1 = {12, 34, 56, 78};
System.out.println(numberOfBeautifulPairs(nums1)); // Output: 4
int[] nums2 = {11, 42, 33, 90};
System.out.println(numberOfBeautifulPairs(nums2)); // Output: 2
}
}
O(n log log n)
where n
is the maximum sum (in this case, 18
).O(n^2)
where n
is the length of the array nums
.O(d)
for each number, where d
is the number of digits (essentially O(1)
operation).Overall, this results in a time complexity of O(n^2)
for this problem with efficient constant-time operations inside the nested loop.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?