Two numbers adding up to K, by Daily Coding Problem

Daily Coding Problem gives you a daily coding problem (LOL) every day (LOL#2). Here is the very first one I got:

Good morning! Here's your coding interview problem for today.
This problem was recently asked by Google.
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?

Notice that it doesn't say that the list contains unique numbers, so you can't assume that and your code needs to handle the case of dupes.
My strategy is the following:

  • Push all the numbers to a hash-table (HT)
  • In the HT each number will have a count corresponding to how many times that number shows up in the list of numbers
  • The code above runs in O(n)-time and O(n)-space
  • Then for each number i, get the difference d=k-i
  • If d is equal to i, make sure that there is at least 2 instances of d in the HT (we're dealing with potential dupes here). If so, return true
  • Otherwise, check whether d is in the HT. If so, return true
  • The code above runs in O(n)-time
  • At this point, all choices have been exhausted, hence return false
Code is below, cheers, Boris.

 static bool TwoSums(int[] arr, int k)
{
Hashtable ht = new Hashtable();

for (int i = 0; i < arr.Length; i++)
{
if (!ht.ContainsKey(arr[i])) ht.Add(arr[i], 1);
else ht[arr[i]] = (int)ht[arr[i]] + 1;
}

for (int i = 0; i < arr.Length; i++)
{
int d = k - arr[i];
if ((d == arr[i] && (int)ht[arr[i]] > 1) || (d != arr[i] && ht.ContainsKey(d))) return true;
}

return false;
}

Comments

  1. Interestingly a single pass solution is actually easier and more intuitive - do the hashtable check during your first pass before you put the number into hashtable (and in fact hashtable is not needed, hashset would do since we only care about presence now because duplicates are now taken care of).

    ReplyDelete
  2. Your place is valueble for me. Thanks!… casino online

    ReplyDelete

Post a Comment

Popular posts from this blog

Count Binary Substrings

Count Vowels Permutation: Standard DP

Maximum Number of Balloons