oneby7

String Matching Pattern matching

581. Z-function

Medium

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"

Output: [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"

Output: [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"

Output: [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.

s = "aaaba"

Constraints

  • 1 ≤ s.length ≤ 106
  • s holds only lowercase English letters.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.