Prepin
Log in

Identify pairs in the array that have a specified difference of k.

Approach / Explanation

This question asks you to find pairs of numbers in an array that have a specific difference, k. You are provided with an array (a collection of numbers) and the target difference k, and your task is to identify pairs of numbers in the array whose absolute difference equals k. Here are some important points to consider: It’s crucial to grasp the concept of absolute difference. The difference between two numbers is the same regardless of which is greater; for instance, the difference between 5 and 3, as well as between 3 and 5, is 2. Keep in mind that the numbers in the list may not be sorted, so your solution should not depend on their order. Remember that each pair must be distinct, meaning you cannot reuse numbers for multiple pairs. A straightforward method would involve iterating over each element and then comparing it with all the other elements to find pairs that have the specified difference. However, this method would be inefficient for larger datasets. A more efficient strategy would be to utilize a hash map or dictionary. By doing this, you can traverse the array just once, storing each element in the dictionary, while simultaneously checking if the corresponding element needed to form a pair already exists in the dictionary. This method is more efficient because checking for the presence of an element in a dictionary is significantly quicker than searching through a list.

Suggested Answer

Here’s an illustration of an effective Python solution utilizing a dictionary: def find_pairs ( arr , k ) : num_dict = { } pairs = [ ] for num in arr : target = k + num if target in num_dict : pairs . append ( ( num , target ) ) num_dict [ num ] = True return pairs Let's test it with an example: arr = [ 1 , 7 , 5 , 9 , 2 , 12 , 3 ] k = 2 print ( find_pairs ( arr , k ) ) This will produce the following output: [(7, 9), (5, 7), (2, 1), (3, 1)] These pairs have a difference of 2.

Alternative Answer

You can also locate pairs with a specified difference using JavaScript: function findPairs ( arr , k ) { let numMap = { } ; let pairs = [ ] ; for ( let i = 0 ; i < arr . length ; i ++ ) { let target = k + arr [ i ] ; if ( numMap [ target ] ) { pairs . push ( [ arr [ i ] , target ] ) ; } numMap [ arr [ i ] ] = true ; } return pairs ; } let arr = [ 1 , 7 , 5 , 9 , 2 , 12 , 3 ] ; let k = 2 ; console . log ( findPairs ( arr , k ) ) ; When you execute the function with the example array, the output will be: [[7,9], [5,7], [2,1], [3,1]] These are the pairs that have a difference of 2.

Question Details

Difficulty & Category

Medium

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.