Daily Coding Problem #2

cwetanow

Ivan

Posted on November 25, 2018

Daily Coding Problem #2

Seeing the first post gained some popularity, here is the second problem

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 #2

This problem was asked by Uber.

Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.

For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].

Follow-up: what if you can't use division?

My solution

using System;
using System.Linq;

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

            var result = new int[input.Length];

            for (int i = 0; i < result.Length; i++)
            {
                result[i] = 1;

                for (int j = 0; j < result.Length; j++)
                {
                    if (j != i)
                    {
                        result[i] *= input[j];
                    }
                }
            }


            Console.WriteLine(string.Join(' ', result));
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation

Here I could not think of any better than the naive solution, which works in O(n^2) time and you never like square complexity.
Basically for every item in the result array, foreach the input array and check if the index is different from the item's. If they are, multiply the current value of the item times the current input item

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 25, 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