Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Daily Coding Problem: Problem #1
/*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?*/ using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Rextester { public class Program { public static void Main(string[] args) { Assert(IsThere(new List<int>(){10, 15, 3, 7}, 17), true, "TEST 1"); Assert(IsThere(new List<int>(){10, 15, 3, 7}, 19), false, "TEST 2"); Assert(IsThere(new List<int>(){10, 10}, 20), true, "TEST 3"); Assert(IsThere(new List<int>(){10}, 20), false, "TEST 4"); Assert(IsThere(new List<int>(){}, 20), false, "TEST 5"); Assert(IsThere(new List<int>(){-5, 5}, 0), true, "TEST 6"); Assert(IsThere(new List<int>(){-5, 6}, 6), false, "TEST 7"); } static bool IsThere(List<int> list, int k) { var dic = list.GroupBy(f => f).ToDictionary(f => f.Key, z => z.Count()); foreach(var el in list) { var need = k - el; if(need == el && dic[el] == 1) { continue; } if(dic.ContainsKey(need)) { return true; } } return false; } static void Assert(bool value, bool shouldBe, string info) { if(value == shouldBe) { Console.WriteLine(info + " passed."); } else { Console.WriteLine(info + " failed."); } } } }
run
|
edit
|
history
|
help
1
Linked List with basic functions.
ProWIN2
Task List
Uninitialized-variable example.
Linq FirstOrDefault() null check in c#
Count vowels in a string
Lazy XML selection
Sri 19 Sept
Lazy exception caching
Fórum ➡ Prime numbers implemented using LINQ statements AND using FOR loop ♦