Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Longest Common Prefix

Easy Acceptance 44.20% Points 20.00

You are given an array of strings, arr[]. Identify and return the longest common prefix shared among all the strings in the array.

  • A prefix is defined as a substring that occurs at the beginning of a string.
  • If there is no common prefix among all the strings, return an empty string "".
Examples
Example 1

Example 1

Input: arr = ["apple", "ape", "april"]

Output: "ap"

Explanation: The longest common prefix among the strings is "ap".

Example 2

Example 2

Input: arr = ["cat", "dog", "fish"]

Output: ""

Explanation: There is no common prefix among the strings.

Hints
Hint 1
Expected Time Complexity: O(n*min(|arri|))
Hint 2
Expected Space Complexity: O(min(|arri|))
Constraints
  • 1 <= |arr| <= 10^3
  • 1 <= |arr[i]| <= 10^3
Companies
Microsoft Samsung Google
Topics
Array String
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions