Intermediate Level

Implement the method longestCommonPrefix that returns the shared starting text of all strings.

Return the longest prefix that appears at the beginning of every string in the input list.

The task is designed to test careful handling of edge cases, not only the most common input.

  • Use only the first size strings.
  • The input contains at least one string.
  • Comparison is case-sensitive.
Example 1
Input:
words (string[]) = ["flower","flow","flight"]
size (int) = 3
Return:
(string) fl
Example 2
Input:
words (string[]) = ["interview","internet","internal"]
size (int) = 3
Return:
(string) inte
Example 3
Input:
words (string[]) = ["same","same"]
size (int) = 2
Return:
(string) same

Start with the first string as the prefix and shorten it until every string starts with it.

Run your code to see the result.