Bootcamps
Masterclasses
Menu
Courses
Account
Login / Sign Up

Longest Common Prefix

Easy Acceptance 44.2% Points 20

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.

Constraints
  • 1 <= |arr| <= 10^3
  • 1 <= |arr[i]| <= 10^3
Hints
  • Expected Time Complexity: O(n*min(|arri|))
  • Expected Space Complexity: O(min(|arri|))
Topics
Array String
Companies
Microsoft Samsung Google
Added 19 Jul 2026 44.2% acceptance
Ln 1, Col 1Sign in to save your code
flower flow flight
fl