Skip to content

2748. Number of Beautiful Pairs 👍

  • Time: $O(n^2)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
 public:
  int countBeautifulPairs(vector<int>& nums) {
    int ans = 0;

    for (int i = 0; i < nums.size(); ++i)
      for (int j = i + 1; j < nums.size(); ++j)
        if (__gcd(firstDigit(nums[i]), lastDigit(nums[j])) == 1)
          ++ans;

    return ans;
  }

 private:
  int firstDigit(int num) {
    return to_string(num)[0] - '0';
  }

  int lastDigit(int num) {
    return num % 10;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
  public int countBeautifulPairs(int[] nums) {
    int ans = 0;

    for (int i = 0; i < nums.length; ++i)
      for (int j = i + 1; j < nums.length; ++j)
        if (gcd(firstDigit(nums[i]), lastDigit(nums[j])) == 1)
          ++ans;

    return ans;
  }

  private int firstDigit(int num) {
    return Integer.parseInt(Integer.toString(num).substring(0, 1));
  }

  private int lastDigit(int num) {
    return num % 10;
  }

  private int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def countBeautifulPairs(self, nums: list[int]) -> int:
    def firstDigit(num: int) -> int:
      return int(str(num)[0])

    def lastDigit(num: int) -> int:
      return num % 10

    return sum(math.gcd(firstDigit(nums[i]), lastDigit(nums[j])) == 1
               for i in range(len(nums))
               for j in range(i + 1, len(nums)))