Skip to content

Commit

Permalink
Solve LeetCode #14 'Longest Common Prefix' [Easy].
Browse files Browse the repository at this point in the history
  • Loading branch information
eminencegrs committed Nov 11, 2024
1 parent c559bb6 commit 9fc7cf6
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
namespace LeetCode.Challenges.Problems0XX.P014_LongestCommonPrefix;

public static class Solution
{
// Explanation:
// 1. If the input array is null or empty, return an empty string, as there's no prefix to find.
// 2. Use the first string in the array as the initial prefix.
// 3. For each subsequent string in the array:
// -- Check if it starts with the current prefix.
// -- If it does not, remove the last character from the prefix and recheck.
// -- Repeat this until the prefix matches the start of the current string or becomes empty.
// 4. If at any point the prefix becomes empty, return an empty string (no common prefix exists).
// 5. After all strings are processed, the prefix will contain the longest common prefix.
public static string LongestCommonPrefix(string[] strings)
{
if (strings == null! || strings.Length == 0)
{
return string.Empty;
}

var prefix = strings[0];
for (var i = 1; i < strings.Length; i++)
{
while (!strings[i].StartsWith(prefix))
{
prefix = prefix.Substring(0, prefix.Length - 1);
if (string.IsNullOrEmpty(prefix))
{
return string.Empty;
}
}
}

return prefix;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using LeetCode.Challenges.Problems0XX.P014_LongestCommonPrefix;
using Shouldly;
using Xunit;

namespace LeetCode.Challenges.UnitTests.Problems0XX.P014_LongestCommonPrefix;

public class SolutionTests
{
[Theory]
[MemberData(nameof(TestData))]
public void GivenStrings_WhenLongestCommonPrefix_ThenResultAsExpected(
string[] strings, string expectedResult)
{
Solution.LongestCommonPrefix(strings).ShouldBe(expectedResult);
}

public static IEnumerable<object[]> TestData()
{
yield return [new[] { "abcd", "abcef", "abcxy" }, "abc"];
yield return [new[] { "flower", "flow", "flight" }, "fl"];
yield return [new[] { "dog", "racecar", "car" }, ""];
yield return [new[] { "apple" }, "apple"];
yield return [new[] { "a", "a", "a" }, "a"];
yield return [new[] { "abc", "abcd", "ab" }, "ab"];
yield return [new[] { "prefix", "preach", "prevent" }, "pre"];
yield return [new[] { "xylophone", "xylene", "xylitol" }, "xyl"];
yield return [new[] { "banana", "band", "banter" }, "ban"];
yield return [new[] { "hello", "world" }, ""];
yield return [Array.Empty<string>(), ""];
}
}

0 comments on commit 9fc7cf6

Please sign in to comment.