Skip to content

Instantly share code, notes, and snippets.

@gladimdim
Last active September 29, 2021 16:27
Show Gist options
  • Save gladimdim/5229bfcc0ec1dcafd8e5066a02b4af0e to your computer and use it in GitHub Desktop.
Save gladimdim/5229bfcc0ec1dcafd8e5066a02b4af0e to your computer and use it in GitHub Desktop.
void main() {
findIfSumIsInArray();
}
/**
Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
Bonus: Can you do this in one pass?
**/
void findIfSumIsInArray() {
List<int> input = [10, -6, 5, 1, 33];
int value = 27;
print("Some $value was found: ${hasSum(input, value)}");
}
bool hasSum(List<int> ar, int sum) {
Set<int> previousValues = {};
for (var el in ar) {
if (previousValues.contains(sum - el)) {
return true;
}
previousValues.add(el);
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment