Skip to content

Commit

Permalink
Added a run for the two-sum problem with reduced time complexity.
Browse files Browse the repository at this point in the history
  • Loading branch information
tacosontitan committed Apr 9, 2024
1 parent 2472bc0 commit 9dc6728
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
39 changes: 39 additions & 0 deletions samples/Hussy.Net.Playground/Leetcode/Easy/TwoSum/ComplexityRun.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using Glitter.Collections;

namespace Hussy.Net.Playground.Leetcode.Easy;

/// <summary>
/// Represents a solution and its tests for the leetcode two-sum problem.
/// </summary>
/// <see href="https://leetcode.com/problems/two-sum/description/"/>
public sealed partial class TwoSum
{
/// <summary>
/// A direct approach to solving the problem with less time complexity
/// to understand where Hussy may be lacking.
/// </summary>
/// <param name="numbers">The array of numbers to look through.</param>
/// <param name="target">
/// The target number which the two numbers in <paramref name="numbers"/> must add up to.
/// </param>
/// <returns>
/// The two indices of the numbers which add up to the <paramref name="target"/>.
/// </returns>
private static IEnumerable<int> ComplexityRun(
int[] numbers,
int target)
{
var seen = new Dictionary<int, int>();
for (var i = 0; i < numbers.Length; i++)
{
var currentNumber = numbers[i];
var complement = target - currentNumber;
if (seen.TryGetValue(complement, out var value))
return [value, i];

seen[currentNumber] = i;
}

return Enumerable.Empty<int>();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ public sealed partial class TwoSum
/// </summary>
private static TestFunction[] TestFunctions =>
[
DryRun
DryRun,
ComplexityRun
];

/// <summary>
Expand All @@ -29,7 +30,7 @@ private static void RunTest(
var resultingSequence = results.ToList();

var excessResults = resultingSequence.Except(expectedSequence);
Assert.True(expectedSequence.All(resultingSequence.Contains));
Assert.True(expectedSequence.TrueForAll(resultingSequence.Contains));
Assert.Empty(excessResults);
}
}
Expand Down

0 comments on commit 9dc6728

Please sign in to comment.