Find a pair with a given difference
Problem
Return true if there are two elements (at different indices) whose difference is exactly n.
Example 1
Input: arr = [5, 20, 3, 2, 50, 80], n = 78 Output: true
80 − 2 = 78.
Also asked as: find a pair with a given difference
Test cases
No automated tests for this problem yet. Use the examples above to check your output.
This problem has no automated tests. Run executes your code and shows what it logs.
View solutionHide solution1 approach
1. Sort + two pointers
Time O(n log n)Space O(1)
Sort ascending. Move two pointers so that a[j] − a[i] converges on the target difference.
function pairWithDiff(a, d) { a.sort((x, y) => x - y); let i = 0, j = 1; while (i < a.length && j < a.length) { const diff = a[j] - a[i]; if (i !== j && diff === d) return [a[i], a[j]]; if (diff < d) j++; else i++; } return null;}