Skip to content

Instantly share code, notes, and snippets.

@gladimdim
Created November 30, 2021 14:09
Show Gist options
  • Save gladimdim/5cf58c74a4c89205aff7271bc01c8f8e to your computer and use it in GitHub Desktop.
Save gladimdim/5cf58c74a4c89205aff7271bc01c8f8e to your computer and use it in GitHub Desktop.
/// https://www.hackerrank.com/challenges/pairs/problem
int findPairs(List<int> pairs, int diff) {
var counter = 0;
// save all values into Set
Set map = {};
for (var el in pairs) {
map.add(el);
// use math to determine if there is a value as difference between value and diff
if (map.contains(el - diff)) {
counter++;
}
// use math to determine if there is a value of sum of element and diff
if (map.contains(el + diff)) {
counter++;
}
}
return counter;
}
void main() {
var input = [1, 2, 3, 4];
var diff = 1;
print("Find pairs in array");
print(findPairs(input, diff));
input = [1, 5, 4, 2];
diff = 2;
print(findPairs(input, diff));
input = [1, 5, 3, 4, 2];
diff = 2;
print(findPairs(input, diff));
input = [1, 3, 5, 8, 6, 4, 2];
diff = 2;
print(findPairs(input, diff));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment