MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / z_function

Function z_function

strings/z_function.py:13–49  ·  view source on GitHub ↗

For the given string this function computes value for each index, which represents the maximal length substring starting from the index and is the same as the prefix of the same size e.x. for string 'abab' for second index value would be 2 For the value of the first element t

(input_str: str)

Source from the content-addressed store, hash-verified

11
12
13def z_function(input_str: str) -> list[int]:
14 """
15 For the given string this function computes value for each index,
16 which represents the maximal length substring starting from the index
17 and is the same as the prefix of the same size
18
19 e.x. for string 'abab' for second index value would be 2
20
21 For the value of the first element the algorithm always returns 0
22
23 >>> z_function("abracadabra")
24 [0, 0, 0, 1, 0, 1, 0, 4, 0, 0, 1]
25 >>> z_function("aaaa")
26 [0, 3, 2, 1]
27 >>> z_function("zxxzxxz")
28 [0, 0, 0, 4, 0, 0, 1]
29 """
30 z_result = [0 for i in range(len(input_str))]
31
32 # initialize interval's left pointer and right pointer
33 left_pointer, right_pointer = 0, 0
34
35 for i in range(1, len(input_str)):
36 # case when current index is inside the interval
37 if i <= right_pointer:
38 min_edge = min(right_pointer - i + 1, z_result[i - left_pointer])
39 z_result[i] = min_edge
40
41 while go_next(i, z_result, input_str):
42 z_result[i] += 1
43
44 # if new index's result gives us more right interval,
45 # we've to update left_pointer and right_pointer
46 if i + z_result[i] - 1 > right_pointer:
47 left_pointer, right_pointer = i, i + z_result[i] - 1
48
49 return z_result
50
51
52def go_next(i: int, z_result: list[int], s: str) -> bool:

Callers 1

find_patternFunction · 0.85

Calls 1

go_nextFunction · 0.85

Tested by

no test coverage detected