String Matching Pattern matching
581. Z-function
You are given a string s of length n. Return its Z-array: a list z of n numbers, one for each
index of s.
For each index i from 1 on, z[i] is the length of the longest piece of s that starts at index i and is
also a prefix of s. In other words, it is the number of letters that match when you read s from the start
and from index i side by side, until the first letter that differs or the end of s. The piece may overlap
the prefix it matches.
By definition, z[0] = 0.
Example 1
Input: s = "abacaba"
[0,0,1,0,3,0,1]Explanation: From index 4 the letters aba match the start of s, and then the string ends, so z[4] = 3. From
index 2 only a matches, because the next letter is c and not b.
Example 2
Input: s = "zzzz"
[0,3,2,1]Explanation: From index 1, all three remaining letters match the start. z[0] is 0 by definition, not 4.
Example 3
Input: s = "banana"
[0,0,0,0,0,0]Explanation: b never appears again, so no index after 0 matches even one letter of the start.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ s.length ≤ 106sholds only lowercase English letters.
Clarifying questions
What you would ask an interviewer before writing any code.