Exclusive Clothing Sale On Flipkart

Get up to 50% off on our latest collection.

Shop Now

Find the Longest Common Prefix in C#

In this article, we will see the longest common prefix in C#

Problem Description

Write a function to find the longest common prefix string amongst all the arrays of strings in C#.

If there is no any common prefix then return an empty string "".

The solution to finding the Longest Common Prefix

Input Example

Example 1

Let the set of strings be { "flower", "flight", "fly", "flow" };

The longest common prefix here is "fl"

Example 2

Let the set of strings be {"dot", "dog", "donkey", "door", "cat" } there is no common prefix here so the longest common prefix is "", which means, an empty string.

Since there is no common prefix at all. 

To find the longest common prefix of a given set of strings in C#, you can use the following algorithm:

  1. Initialize a variable prefix to an empty string.
  2. If the input array is empty, return the empty string.
  3. Sort the input array in lexicographic order.
  4. Iterate over the characters in the first string in the sorted array.
  5. For each character, compare it to the corresponding character in the other strings in the array. If any of the characters don't match, return the current prefix.
  6. If all the characters match, append the current character to the prefix.
  7. Return the prefix.

Here is the C# code that implements this algorithm:

public class LongestCommonPrefix {
    public static string LongestCommonPrefixFun(string[] input) {
        if (input.Length == 0) {
            return "";
        }
        Array.Sort(input);
        string prefix = "";
        for (int i = 0; i < input[0].Length; i++) {
            char c = input[0][i];
            for (int j = 1; j < input.Length; j++) {
                if (i >= input[j].Length || input[j][i] != c) {
                    return prefix;
                }
            }
            prefix += c;
        }
        return prefix;
    }
}
C#

You can call this method with an array of strings as an argument, like this:

string[] input = { "flower", "flight", "fly", "flow" };
string result = LongestCommonPrefix.LongestCommonPrefixFun(input);
Console.WriteLine("Longest Common Prefix is- " + result); // Output: "fl"
C#

This code will output "fl", which is the longest common prefix of the input strings "flower""flight", "flow", and "flight".


Output





-----------------------------------------------------

Share this

Related Posts

Previous
Next Post »

Exclusive Clothing Sale On Flipkart

Get up to 50% off on our latest collection.

Shop Now