Leetcode 2748: Number of Beautiful Pairs

grid47
grid47
Exploring patterns and algorithms
Feb 6, 2024 5 min read

You are given an array ’nums’ containing integers. A pair of indices ‘i, j’ is considered beautiful if the first digit of nums[i] and the last digit of nums[j] are coprime. Two numbers are coprime if their greatest common divisor (GCD) is 1, i.e., ‘gcd(x, y) == 1’. Your task is to find the total number of beautiful pairs in nums.
Problem
Approach
Steps
Complexity
Input: You will be given an array of integers 'nums'. Each element in 'nums' is an integer with 1 to 4 digits.
Example: nums = [4, 15, 33, 17]
Constraints:
• 2 <= nums.length <= 100
• 1 <= nums[i] <= 9999
• nums[i] % 10 != 0
Output: Return the total number of beautiful pairs in the given array.
Example: For nums = [4, 15, 33, 17], the output is 6.
Constraints:
• The output is an integer representing the number of beautiful pairs.
Goal: Identify all pairs i, j such that the first digit of nums[i] and the last digit of nums[j] are coprime.
Steps:
• Iterate over all possible pairs of indices i, j where i < j.
• Extract the first digit of nums[i] and the last digit of nums[j].
• Check if the GCD of the first digit and last digit is 1 using the 'gcd' function.
• Count the pairs where GCD is 1.
Goal: Ensure that nums has at least 2 elements and each element in nums is between 1 and 9999, and its last digit is not 0.
Steps:
• 2 <= nums.length <= 100
• 1 <= nums[i] <= 9999
• nums[i] % 10 != 0
Assumptions:
• The input will always contain valid integers in the range 1 to 9999.
Input: For nums = [4, 15, 33, 17]
Explanation: You need to check every possible pair (i, j) where i < j and verify if the first digit of nums[i] and the last digit of nums[j] are coprime. The GCD of these digits should be 1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus