← DiffPush

Longest common prefix

Baseline Strings · Easy O(N*M*log(N)) · O(1)

Shared Root of the Wing Access Codes

A facility issues door-access codes in families, where every code in a family begins with the same leading segment that routes the request to the right wing. The panel firmware receives a batch of candidate codes and must display their common opening segment for the operator. When the codes share nothing up front, the display simply stays blank.

Input: An array of strings strs.

Output: The longest string that is a prefix of every string in strs, or "" when no common prefix exists.

Constraints

Examples

Example 1

Input: {"strs":["flower","flow","flight"]}
Output: "fl"
All three codes open with f followed by l; the third character already differs across the batch.

Example 2

Input: {"strs":["dog","racecar","car"]}
Output: ""
The first characters disagree immediately, so the batch has no shared opening segment.

Solve this in your browser →

Also on LeetCode ↗