Problem Description
Given an integer array nums, count the number of beautiful pairs (i, j) where 0 <= i < j < nums.length such that the first digit of nums[i] and the last digit of nums[j] are coprime. Two integers are coprime if their greatest common divisor (gcd) is 1.
Key Insights
- The input size is small (nums.length between 2 and 100), so an O(n²) solution is acceptable.
- Extracting the first digit of a number can be done by repeatedly dividing by 10 (or converting to a string).
- The last digit of a number is simply nums[j] % 10.
- Use gcd to check if two numbers are coprime.
- Iterate through all pairs with i < j, compute the required digits, and count the pair if they are coprime.
Space and Time Complexity
Time Complexity: O(n²) – since we examine every pair of indices. Space Complexity: O(1) – only constant extra space is used.
Solution
We loop through the array with two indices (i and j) ensuring i < j. For each pair, we extract: • The first digit of nums[i] by repeatedly dividing by 10 until the number is less than 10. • The last digit of nums[j] using modulo operation (nums[j] % 10). Then, we calculate the gcd of these two digits. If the gcd is 1, the digits are coprime and we increment our count. This straightforward approach leverages basic arithmetic operations and the math gcd function.