Frontend School

Find Pair with Absolute Difference K

DSA
easy

Find Pair with Absolute Difference K

Easy
Arrays
Hashing

Overview

Imagine you're analyzing sensor data from a financial trading system, where readings represent price fluctuations. To detect significant market events, you often need to quickly identify if any two sensor readings differ by a specific threshold k. This problem challenges you to determine if such a pair of readings exists within a given set of integer data points.

What you need to do / Task

Implement a function findPairWithAbsoluteDifferenceK that takes an array of integers nums and an integer k. The function should return true if there exist two distinct indices i and j in nums such that |nums[i] - nums[j]| == k. Otherwise, return false.

Input & output

Function Signature: function findPairWithAbsoluteDifferenceK(nums: number[], k: number): boolean

  • nums: An array of integers representing the data points.
  • k: An integer representing the target absolute difference.
  • Returns: boolean - true if a pair with the specified absolute difference exists, false otherwise.

Clarifications

  • Distinct Indices: The problem explicitly requires i != j. If k = 0, this means you are looking for duplicate numbers in the array.
  • Negative Numbers: nums can contain negative integers.
  • Large Values: nums[i] and k can be large, but intermediate calculations should fit standard integer types (e.g., JavaScript's number type).

Examples

1

Example 1

Input:

nums = [1, 5, 3, 9], k = 2

Output:

true

Note:

The pair (1, 3) has an absolute difference of 2. (Alternatively, (5, 3) also has an absolute difference of 2.)

2

Example 2

Input:

nums = [1, 2, 3, 4, 5], k = 7

Output:

false

Note:

No two distinct numbers in the array have an absolute difference of 7.

3

Example 3

Input:

nums = [1, 1, 3, 4], k = 0

Output:

true

Note:

The pair (1, 1) at distinct indices (e.g., 0 and 1) has an absolute difference of 0.

4

Example 4

Input:

nums = [-5, -2, 0, 3], k = 3

Output:

true

Note:

The pair (-5, -2) has an absolute difference of |-5 - (-2)| = |-3| = 3.

Constraints

Constraints & assumptions

  • 2 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • 0 <= k <= 2 * 10^9
  • Expected time complexity: O(N) or O(N log N)
  • Expected space complexity: O(N)

What interviewers evaluate

  • Correctness: Does the solution correctly identify pairs for all valid inputs, including edge cases like k=0, negative numbers, and arrays with duplicates?
  • Efficiency: Is the chosen algorithm optimal in terms of time and space complexity given the constraints?
  • Clarity & Readability: Is the code well-structured, easy to understand, and follow best practices for the chosen language?
  • Problem-solving: Can the candidate articulate their thought process, explain the algorithm, and justify their design choices?

Loading editor...