A recursive solution that checks for each item x in the list if there is an item in the rest of the list that, added to x, results in the target value.
C#, with comments on every line, so that everyone can understand it even if they don't speak the language:
The simple, O(n2) solution - using a nested loop.
(intIndex1,intIndex2)TwoSum(int[]array,inttarget){// iterate the array from 0 to length -2for(vari=0;i<array.Length-1;i++){// iterate the array from i+1 to length -1for(varj=i+1;j<array.Length;j++){// if sum foundif(array[i]+array[j]==target){// return both indexesreturn(i,j);}}}// indicate no match found, required by the c# compier.return(-1,-1);}
The sophisticated, O(n) solution - using a single loop and a helper hash map.
intIndex1,intIndex2)TwoSumImproved(int[]array,inttarget){// In .Net, A dictionary is basically a hash map. here the keys and values are both intsvarmap=newDictionary<int,int>();// iterate the full length of the array.for(vari=0;i<array.Length;i++){// calculate the value needed to add to the current value to get the target sumvarvalueNeeded=target-array[i];// check if the map contains the value needed as it's key, If it does, return true and populate the int j// The TryGetValue time complexity is approaching O(1)if(map.TryGetValue(valueNeeded,outintj)){// return both indexesreturn(j,i);}// add to the map, where the key is the array value and the value is the index.map.Add(array[i],i);}return(-1,-1);// indicate no match found}
19 yo student *and* a full-time developer.
Building with Rails currently, exploring new frontiers.
I enjoy functional programming, Linux, FOSS, refactoring and mentoring :)
The initial solution comes to mind which obviously could be improved in performance purposes having more time
def two_sum(array, target)
array.each_with_index do |item, i|
(i + 1).upto(array.size - 1) do |j|
return [i, j] if item + array[j] == target
end
end
nil
end
Coding since 11yo, that makes it over 30 years now ~~~
Have a PhD in Comp Sci ~~~
Love to go on bike tours ~~~
I try to stay as generalist as I can in this crazy wide place coding is at now.
The partials map maps the index of each value to the value required to bring it up to the target. This can then be picked up by a later value to the get the answer.
I know the question said the input is always good, but I didn't want to ignore possible errors in when using the function...
I'm not sure of the speed of this code either. My guess is it only evaluates combinations until it finds a correct one? But I'm not an expert on lazy evaluation and I'm pretty sure this could be faster.
Perl solution. Walk the array, for each element, store the expected counterpart into a hash. If the element already exists in the hash, we have the pair.
globalsum_valuesum_value=int(input("Enter the sum value :"))arr=[int(i)foriininput("Enter array elements :").split()]deftwo_sum(arr):foriinrange(len(arr)):forjinrange(i+1,len(arr)):ifarr[j]+arr[i]==sum_value:return(i,j)return"NO SUCH PAIRS FOUND"print(two_sum(arr))
Another one
globalsum_valuesum_value=int(input("Enter the sum value :"))arr=[int(i)foriininput("Enter array elements :").split()]deftwo_sum(arr):foriinrange(len(arr)):second_num=sum_value-arr[i]ifsecond_numinarr:return(i,arr.index(second_num))return"NO SUCH PAIRS FOUND"print(two_sum(arr))
def twoSum(arr,target):
for i in range(len(arr)-1):
for j in range(i+1,len(arr)):
if(arr[i]+arr[j]==target):
return([i,j])
else:
return("no indices found with that sum")
if __name__=="__main__":
arr=list(map(int,input().split()))
target=int(input())
print(twoSum(arr,target))
Haskell
A recursive solution that checks for each item
xin the list if there is an item in the rest of the list that, added tox, results in the target value.The input will always be valid that's even worst than premature optimizations.
However, for the purpose of this challenge, I'll take that assumption, because while super important, input validation is boring.
My answer inspired by willsmart's answer.
C#, with comments on every line, so that everyone can understand it even if they don't speak the language:
The simple, O(n2) solution - using a nested loop.
The sophisticated, O(n) solution - using a single loop and a helper hash map.
Try it online
Inspired by Michael Kohl's solution in F# (O(n) rules!), I did the same thing in Rust. All the credit to him :)
JavaScript
Recursive solution.
Try it online.
Ruby
The initial solution comes to mind which obviously could be improved in performance purposes having more time
reduceis good for this one.Here's a JS quickie with O(n) complexity.
The
partialsmap maps the index of each value to the value required to bring it up to the target. This can then be picked up by a later value to the get the answer.In gwion:
The fun thing is that it undercovered a (now fixed) bug on tuple unpacking. 🍾
Here is the Python solution:
Haskell:
I know the question said the input is always good, but I didn't want to ignore possible errors in when using the function...
I'm not sure of the speed of this code either. My guess is it only evaluates combinations until it finds a correct one? But I'm not an expert on lazy evaluation and I'm pretty sure this could be faster.
Perl solution. Walk the array, for each element, store the expected counterpart into a hash. If the element already exists in the hash, we have the pair.
Another one
In Python, written with a O(n) solution with the given assumptions using a dictionary and enumeration to generate an index.
class Solution {
static func twosum(numbers: [Double], target: Double) -> [Int] {
let result = numbers.filter({ return numbers.contains( target - $0 ) })
return [numbers.firstIndex(of: result[0])! , numbers.lastIndex(of: result [result.count - 1 ] )!] }
}
The target example is given as:
But I believe that should be something like:
correct?
No, because it returns the indices, not the values.
OH! missed that :) Thanks!
def twoSum(arr,target): for i in range(len(arr)-1): for j in range(i+1,len(arr)): if(arr[i]+arr[j]==target): return([i,j]) else: return("no indices found with that sum") if __name__=="__main__": arr=list(map(int,input().split())) target=int(input()) print(twoSum(arr,target))Swift Solution
class Solution {
static func twosum(numbers: [Double], target: Double) -> [Int] {
let result = numbers.filter({ return numbers.contains( target - $0 ) })
return [numbers.firstIndex(of: result[0])! , numbers.lastIndex(of: result [result.count - 1 ] )!] }
}