I am writing a function that, given a list and a target sum, returns zero-based indices of any two distinct elements whose sum is equal to the target sum. If there are no such elements, the function should return null.
For example,
FindTwoSum(new List<int>() { 1, 3, 5, 7, 9 }, 12)
should return any of the following tuples of indices:
1, 4 (3 + 9 = 12)
2, 3 (5 + 7 = 12)
3, 2 (7 + 5 = 12)
4, 1 (9 + 3 = 12)
Note: I made my code return the first sum equal to 12.
So far, I came up with the following:
using System;
using System.Collections.Generic;
class TwoSum
{
public static Tuple<int, int> FindTwoSum(IList<int> list, int sum)
{
int first_i =0, global_sum=0, second_i=1;
if(list.Count == 0 || sum == 0 ){
return null;
}
for(int i = first_i ; i< list.Count; i++)
{
for(int j=second_i; j<list.Count; j++)
{
if(i != list.Count)
{
global_sum += list[i] + list[j];
if(global_sum == sum)
{
var tuple1 = Tuple.Create(i,j);
return tuple1;
}
global_sum = 0;
}
else
{
break;
}
}
}
return null;
}
public static void Main(string[] args)
{
Tuple<int, int> indices = FindTwoSum(new List<int>() { 1, 3, 5, 7, 9 }, 12);
Console.WriteLine(indices.Item1 + " " + indices.Item2);
}
}
Everything was working fine and I scored 75%. But in terms of performance, my code did badly as I got a review saying:
performance test- The code too long to calculate an answer. Analyse how your code behaves when the input increases in size and see if you can make it work faster