FastPrepPearson Correlation Coefficient
Problems/Pearson Correlation Coefficient

Pearson Correlation Coefficient

Headlands Technologies logoHeadlands Technologies● MediumFULLTIMEPHONE SCREEN
QuestionFunctionExamplesConstraints

Problem statement

Source note: The report asks for correlation calculated by hand on two random NumPy sequences and checked with NumPy. This reproducible practice version supplies paired arrays, uses Pearson correlation and excludes constant sequences; these numeric and input conventions were not reported. Approximate source match: 75%.

Given two equal-length arrays x and y of paired observations, calculate their Pearson correlation coefficient without a statistics library.

Let mx and my be their arithmetic means. Return sum((x[i] - mx) * (y[i] - my)) / sqrt(sum((x[i] - mx)^2) * sum((y[i] - my)^2)). Each sum includes every index.

Both arrays have positive variance, so the denominator is nonzero. Keep the sign of the result; do not return covariance or its absolute value. The judged result uses absolute or relative tolerance 1e-6.

The arrays are provided so each run is reproducible. In a Python study session, you can also generate paired random arrays and check your calculation with numpy.corrcoef(x, y)[0, 1]; the judged implementation needs no NumPy dependency.

Function

correlation(x: double[], y: double[]) → double

Examples

Example 1

x = [1,2,3]y = [2,4,6]return = 1.0

A positive linear relationship has correlation 1.

Example 2

x = [1,2,3]y = [6,4,2]return = -1.0

A negative linear relationship has correlation -1.

Example 3

x = [-1,0,1]y = [1,0,1]return = 0.0

Centered cross-products cancel, while both variances are positive.

Constraints

  • 2 <= x.length == y.length <= 100000.
  • Each observation is a finite integer represented as a double, with absolute value at most 1000000.
  • Each array contains at least two different values.
  • Use double-precision arithmetic. NaN, infinities and constant arrays are outside the input contract.

More Headlands Technologies problems

  • Integer Compression OffsetPHONE SCREEN · Seen Oct 2026
  • Array Interval SumsOA · Seen Oct 2026
  • Job Runner Chain ReportsOA · Seen Oct 2026
All Headlands Technologies interview questionsSee Headlands Technologies hiring insights
Saved
class Solution {
    public double correlation(double[] x, double[] y) {
        // write your code here
    }
}
Checking account…