This post is part of a series on Mohammad Anwar’s excellent Weekly Challenge, where hackers submit solutions in Perl, Raku, or any other language, to two different challenges every week. (It’s a lot of fun, if you’re into that sort of thing.)
Task #1 this week is to implement the Diff-K algorithm, as explained by Mohammad:
You are given an array @N of positive integers (sorted) and another non negative integer k. Write a script to find if there exists 2 indices i and j such that A[i] – A[j] = k and i != j.
This one is pretty easy. We can boil down the solution into two operations for each element ($_) of @N:
- First, filter @N for elements where $k+$_ exists in @N.
- For the remaining elements, return an array containing the indexes of $k+$_ and $_.
To make this easier and more efficient, we’ll create an %idx_of hash to store the index of each element in @N. This can be created in linear time, and gives us O(1) lookups for both operations, above.
I really like how easy it is to create a reverse hash like this in Raku:
my %idx_of = @N.antipairs;