Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Check for a pair with difference K in a sorted array

Given a sorted array of integers and a non-negative integer K, determine whether any two distinct elements have an absolute difference equal to K.

Python practice8 minTwo Pointers & Sliding WindowBeginnerLast updated March 26, 2026

Problem statement

You are given a sorted (non-decreasing) list of integers nums and a non-negative integer k. Determine whether there exist two distinct indices i and j such that |nums[i] - nums[j]| == k. Return True if such a pair exists, otherwise return False. Notes: - The input array is sorted in non-decreasing order. - k is guaranteed to be >= 0. - Aim for O(n) time and O(1) extra space using the two-pointer approach.

Task

Use the two-pointer technique on a sorted array to find if any pair has absolute difference K in linear time and constant extra space.

Examples

Basic example

Input

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

Output

True

3 and 7 would be a candidate but 5 and 1 differ by 4 (5 - 1 = 4). There exists a pair with difference 4.

Input format

Two arguments: a sorted list of integers nums and a non-negative integer k.

Output format

Return True if any two distinct elements have absolute difference k, otherwise False.

Constraints

0 <= len(nums) <= 10^5, -10^9 <= nums[i] <= 10^9, 0 <= k <= 10^9. Time target: O(n), extra space: O(1).

Samples

Sample 1

Input

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

Output

True

There are duplicate elements (2 and 2) so difference 0 exists.