Daily Coding Problem #1

cwetanow

Ivan

Posted on November 24, 2018

Daily Coding Problem #1

For quite some time I found my time procastinating after getting home from work. Untill a few days ago I stumbled upon the Daily Coding Problem (DCP) and decided to give it a shot.
The code is in C#.

How it works?

The folks at DCP send you a problem that was asked at a top company everyday for you to solve. The premium membership also offers the opportunity to verify your solution.

Problem #1

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?

My solution

using System;
using System.Collections.Generic;
using System.Linq;

namespace Problem01
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var numbers = Console.ReadLine()
                .Split(' ')
                .Select(int.Parse)
                .ToList();

            var k = int.Parse(Console.ReadLine());

            var result = TwoNumbersEqual(numbers, k);
            Console.WriteLine(result);
        }

        public static bool TwoNumbersEqual(List<int> numbers, int k)
        {
            var set = new HashSet<int>();

            foreach (var number in numbers)
            {
                var remaining = k - number;

                if (set.Contains(remaining))
                {
                    return true;
                }

                set.Add(number);
            }

            return false;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation

The naive solution would be to do two nested for loops and check if any of the combinations gives the k we desire.
But because I wanted the bonus tag and after some tought, I realized that you could foreach the input array and for each item check find the difference between it and k. After you find the difference, you can check if you have already seen this number before and the HashSet data structure allows for constant lookups (because it is a hash table).

I will try to do the daily problem everyday, but sometimes life gets in the way :)
Solutions are posted in my github account




.

Feel free to leave a like and let me know in the comments if I should continue to post my solutions.

If you also have any better solution in mind, by all means share it, so we can learn from each other.

💖 💪 🙅 🚩
cwetanow
Ivan

Posted on November 24, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Daily Coding Problem #4
dev Daily Coding Problem #4

January 2, 2020

Daily Coding Problem #1
dev Daily Coding Problem #1

November 24, 2018

Daily Coding Problem #2
dev Daily Coding Problem #2

November 25, 2018

Daily Coding Problem #3
dev Daily Coding Problem #3

November 26, 2018