Leetcode 2748. Number of Beautiful Pairs
Given an array of positive integers nums, a pair (i, j) is called beautiful if 1 <= i < j <= nums.length and the greatest common divisor (GCD) of the first digit of nums[i] and the last digit of nums[j] is 1. Return the number of beautiful pairs in the array nums.
nums?nums?nums contains only one element?nums, extract the first and the last digits.__gcd function from the <numeric> library to check if the GCD of the first digit of nums[i] and the last digit of nums[j] is 1.(i, j) where 1 <= i < j <= nums.length and count those pairs which meet the condition.#include <iostream>
#include <vector>
#include <numeric> // for __gcd function
int firstDigit(int num) {
while (num >= 10) {
num /= 10;
}
return num;
}
int lastDigit(int num) {
return num % 10;
}
int countBeautifulPairs(const std::vector<int>& nums) {
int n = nums.size();
int beautifulPairsCount = 0;
for (int i = 0; i < n; ++i) {
int firstDigitI = firstDigit(nums[i]);
for (int j = i + 1; j < n; ++j) {
int lastDigitJ = lastDigit(nums[j]);
if (std::gcd(firstDigitI, lastDigitJ) == 1) {
beautifulPairsCount++;
}
}
}
return beautifulPairsCount;
}
int main() {
std::vector<int> nums = {13, 25, 32, 49};
std::cout << "Number of beautiful pairs: " << countBeautifulPairs(nums) << std::endl;
return 0;
}
(i, j) have a time complexity of (O(n^2)).Hence, the overall time complexity is (O(n^2)) where (n) is the length of nums.
This solution efficiently and clearly identifies the number of beautiful pairs by leveraging straightforward algorithm constructs and the properties of GCD.
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?