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
Returns (string) fl

Example 2

Input
words (string[]) = ["interview","internet","internal"]
size (int) = 3
Returns (string) inte

Example 3

Input
words (string[]) = ["same","same"]
size (int) = 2
Returns (string) same

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

Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.