Wednesday, June 3, 2015

TwoSum (C#) : Algorithm

Write 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)

E.g

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. class TwoSum
  5. {
  6.     public static Tuple<int, int> FindTwoSum(IList<int> list, int sum)
  7.     {
  8.         throw new NotImplementedException("Waiting to be implemented.");
  9.     }
  10.  
  11.     public static void Main(string[] args)
  12.     {
  13.         Tuple<int, int> indices = FindTwoSum(new List<int>() { 1, 3, 5, 7, 9 }, 12);
  14.         Console.WriteLine(indices.Item1 + " " + indices.Item2);
  15.     }
  16. }

Solved Code Snippet
  1. using System;
  2. using System.Linq;
  3. using System.Collections.Generic;
  4.  
  5. class TwoSum
  6. {
  7.     public static Tuple<int, int> FindTwoSum(IList<int> list, int sum)
  8.     {
  9.         var result = from n1 in list
  10.                      from n2 in list
  11.                      where n1 + n2 == sum
  12.                      select new Tuple<int, int>(list.IndexOf(n1), list.IndexOf(n2));
  13.         return result.FirstOrDefault();
  14.     }
  15.  
  16.     public static void Main(string[] args)
  17.     {
  18.         Tuple<int, int> indices = FindTwoSum(new List<int>() { 1, 3, 5, 7, 9 }, 12);
  19.         Console.WriteLine(indices.Item1 + " " + indices.Item2);
  20.     }
  21. }

1 comment:

Unknown said...

The solution looks nice but is far from optimal. Unfortunatelly, for a large number of elements it will exceed the time limit (if you solve this task as part of a programming competition). There is a better solution for this problem.