11/07/2021

[Java] Find all pairs with difference K in array

Given an array of unique integers and a target K, find all pairs of elements that satisfy the formula X - Y = K

The output should preserve the order of elements for Y. Example:

0,-1,1 target 1 result: (1,0), (0, -1)

We can add all elements to a set, then walk the array again and consider each element as the Y in the equation.

We then check if the complement X = K + Y is in the set, and if so, we add it to the output.

We can do this in O(N) time and space.

You can check my implementation of pairsWithDifferenceK on my Gist along with some tests in PairsWithDifferenceKJTests.

No comments:

Post a Comment

With great power comes great responsibility