FastPrepGet Perfect Pairs Count

Get Perfect Pairs Count

Salesforce logoSalesforce● MediumFULLTIMEOA

Problem statement

A pair of Integers (x, y) is perfect if both of the following conditions are met:

  • min(|x - y|, |x + y|) ≤ min(|x|, |y|)
  • max(|x - y|, |x + y|) ≥ max(|x|, |y|)

Given an array arr of length n, find the number of perfect pairs (arr[i], arr[j]) where 0 ≤ i < j < n.

Here min(a, b) is the minimum of a and b, max(a, b) is the maximum of a and b, and |x| is the absolute value of x.

Function

getPerfectPairsCount(arr: int[]) → int

Complete the function getPerfectPairsCount in the editor.

getPerfectPairsCount has the following parameter:

  • int arr[n]: an array of integers

Returns int: the number of perfect pairs

Examples

Example 1

arr = [2, 5, -3]return = 2

In this example, n = 3. The possible pairs are (2, 5), (2, -3) and (5, -3).

  • (2, 5) is not perfect
    • min(|2 - 5|, |2 + 5|) = 3, min(|2|, |5|) = 2
      • It fails the first test: 3 > 2
  • (2, -3) is perfect
    • min(|5|, |-1|) = 1, min(|2|, |-3|) = 2
      • It passes the first test: 1 ≤ 2
    • max(|5|, |-1|) = 5, max(|2|, |-3|) = 3
      • It passes the second test: 5 ≥ 3
  • (5, -3) is perfect
    • min(|8|, |2|) = 2, min(|5|, |-3|) = 3
      • It passes the first test: 2 ≤ 3
    • max(|8|, |2|) = 8, max(|5|, |-3|) = 5
      • It passes the second test: 8 ≥ 5

Therefore, there are 2 perfect pairs.

Constraints

  • 2 ≤ n ≤ 2*105
  • -109 ≤ arr[i] ≤ 109

More Salesforce problems

See Salesforce hiring insights
Saved
public int getPerfectPairsCount(int[] arr) {
  // write your code here
}
arr[2, 5, -3]
expected2
Checking account…