Shortest Contiguous Sum, by Lyft
This one comes from Lyft, by Daily Coding Problem:
I changed the problem a bit so that you should return the shortest contiguous array that sums up to K.
The O(N^2)-time solution is trivial (two tested loops, keeping track of the shortest length).
There is an O(N)-time which goes like this:
This problem was asked by Lyft.
Given a list of integers and a number K, return which contiguous elements of the list sum to K.
For example, if the list is [1, 2, 3, 4, 5] and K is 9, then it should return [2, 3, 4].
The O(N^2)-time solution is trivial (two tested loops, keeping track of the shortest length).
There is an O(N)-time which goes like this:
- Keep a variable holding the sum from 1.. up to "i"
- Hash table that sum, with the value being the index "i"
- Then, always check to see if sum - k has already been added to the hash table
- If so, then get that index, call it j
- The shortest contiguous sum will be from j+1..i, unless j == i, in which case the solution is a single number (i..i)
For this input for example:
Numbers = {-3 0 -1 2 -3 4 -6 12 13 -6 -7 7 8}
K=21
The solution should be the highlighted.
O(N)-time, but using some extra space, max of O(N)-space. Code is on Gitgub here: https://github.com/marcelodebarros/dailycodingproblem/blob/master/DailyCodingProblem12252018.cs and also down below, cheers, Marcelo
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DailyCodingProblem
{
class DailyCodingProblem12252018
{
public void ContiguousElementsSum(int[] numbers, int k)
{
Hashtable sumToIndex = new Hashtable();
int shortestStartIndex = -1;
int shortestLength = Int32.MaxValue;
int sum = 0;
for (int i = 0; i < numbers.Length; i++)
{
sum += numbers[i];
if (!sumToIndex.ContainsKey(sum)) sumToIndex.Add(sum, i);
else sumToIndex[sum] = i;
int delta = sum - k;
if (sumToIndex.ContainsKey(delta))
{
int startIndex = Math.Min((int)sumToIndex[delta] + 1, i);
if (i - startIndex + 1 < shortestLength)
{
shortestLength = i - startIndex + 1;
shortestStartIndex = startIndex;
}
}
}
if (shortestStartIndex >= 0)
{
Console.WriteLine("Shortest contiguous sum to {0}: [{1}, {2}]", k, shortestStartIndex, shortestStartIndex + shortestLength - 1);
}
else
{
Console.WriteLine("Sum not found");
}
}
}
}
Comments
Post a Comment