Skip to the code
cf.
+25 XP

#619 Prefix Match Lengths

medium

A text tool shows, under every character of a line, how far the text starting there agrees with the start of the line. Long agreements hint at repeated headers.

Write prefixMatches(text) that returns an array z of the same length, where z[i] is the length of the longest substring starting at i that is also a prefix of text. By convention z[0] is text.length.

Lines can be 100,000 characters long, so comparing from every position separately is too slow.

Example 1

Input: text = "aabxaab"
Output: [7,1,0,0,3,1,0]

At index 4, aab matches the first three letters.

Example 2

Input: text = "aaaa"
Output: [4,3,2,1]

From index 1, aaa matches the start, and so on.

Constraints

  • 0 <= text.length <= 10^5
  • text contains lowercase letters.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).