Last active
September 29, 2021 16:27
-
-
Save gladimdim/5229bfcc0ec1dcafd8e5066a02b4af0e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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