Analysis
The brute force way would be to check every two digits from the given list. This would be a O(n^2)
solution which is not very useful. The other option I thought of was to sort the array first. Unfortunately, for the given problem sorting would accomplish nothing. Is there a way to solve this in O(n)
time? Perhaps, if we could trade some extra space for time.
EDIT: sorting is actually useful! Have a look at Two Sum II.
First Attempt
1 | class Solution { |
The first attempt failed. I failed to read the complete requirement. The question is asking for a list of indices π. And the other problem with this solution is that we are inserting remainder as well. This is wrong π!!! We end up inserting numbers into the set that donβt even exist in the input.
Accepted
1 | class Solution { |
Lesson learned
Please read the question more carefully!!!