Saturday, May 23, 2015

Longest Common Prefix

Problem Statement

Write a function to find the longest common prefix string amongst an array of strings.

Source: https://leetcode.com/problems/longest-common-prefix/
Programming Language: C#
Run Time Complexity: if n is the length of shortest string in array of strings and there are m strings in the array. Run time complexity would be O(m*n)
Space Complexity: Constant space

Solution

public string LongestCommonPrefix(string[] strs)
{
    // Input Validation
    if ((strs == null) || (strs.Length <= 0))
        return "";

    // First string in the array of Strings
    string firstString = strs[0];

    // If the length of array of strings is 1 you can return the first string
    if (strs.Length == 1)
        return firstString;
    
    // For all characters in the first string
    for (int index = 0; index < firstString.Length; index++)
    {
        // Index for the string array
        for (int strsIndex = 1; strsIndex < strs.Length; strsIndex++)
        {
            // Condition 1: index should be less than the current string in the array
            // Condition 2: character at index should match with the character of the current string
            if ((index > strs[strsIndex].Length - 1) || (strs[strsIndex][index] != firstString[index]))
                return firstString.Substring(0, index);
        }
    }

    // If first string is ended that is the common prefix 
    return firstString;
}

No comments:

Post a Comment