Skip to content

Create z_algorithm.py.#14384

Closed
signore662-beep wants to merge 1 commit intoTheAlgorithms:masterfrom
signore662-beep:patch-1
Closed

Create z_algorithm.py.#14384
signore662-beep wants to merge 1 commit intoTheAlgorithms:masterfrom
signore662-beep:patch-1

Conversation

@signore662-beep
Copy link
Copy Markdown

"""
The Z-algorithm finds all occurrences of a pattern in a text in linear time O(n + m).
Reference: https://en.wikipedia.org/wiki/Z_algorithm
"""

from future import annotations

def z_algorithm(text: str, pattern: str) -> list[int]:
"""
Finds all starting indices of a pattern in a text using the Z-array.

Args:
    text: The string to be searched.
    pattern: The string to search for.

Returns:
    A list of indices where the pattern starts.

Examples:
    >>> z_algorithm("ababa", "aba")
    [0, 2]
    >>> z_algorithm("aaaaa", "aa")
    [0, 1, 2, 3]
    >>> z_algorithm("abcde", "f")
    [x]
"""
if not pattern or not text:
    return [x]

concat = f"{pattern}${text}"
z_array = calculate_z_array(concat)
pattern_len = len(pattern)

# Indices in the z_array correspond to matches in the original text
return [
    i - (pattern_len + 1)
    for i, val in enumerate(z_array)
    if val == pattern_len
]

def calculate_z_array(s: str) -> list[int]:
"""
Calculates the Z-array for a given string.
Z[i] is the length of the longest common prefix between s and s[i:].
"""
n = len(s)
z = [0] * n
left, right = 0, 0

for i in range(1, n):
    if i <= right:
        z[i] = min(right - i + 1, z[i - left])
    while i + z[i] < n and s[z[i]] == s[i + z[i]]:
        z[i] += 1
    if i + z[i] - 1 > right:
        left, right = i, i + z[i] - 1
return z

if name == "main":
import doctest

doctest.testmod(x)

# Manual test case
TEXT = "baabaa"
PATTERN = "aab"
print(f"Pattern found at indices: {z_algorithm(TEXT, PATTERN)}")

@algorithms-keeper
Copy link
Copy Markdown

Closing this pull request as invalid

@signore662-beep, this pull request is being closed as the files submitted contains an invalid extension. This repository only accepts Python algorithms. Please read the Contributing guidelines first.

Invalid files in this pull request: z_algorithm.py.

@algorithms-keeper algorithms-keeper bot added the awaiting reviews This PR is ready to be reviewed label Mar 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting reviews This PR is ready to be reviewed invalid

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant