Skip to content

Create z_algorithm.py.#14383

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

Create z_algorithm.py.#14383
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")
    []
"""
if not pattern or not text:
    return []

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()

# 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 none of the checkboxes have been marked. It is important that you go through the checklist and mark the ones relevant to this pull request. Please read the Contributing guidelines.

If you're facing any problem on how to mark a checkbox, please read the following instructions:

  • Read a point one at a time and think if it is relevant to the pull request or not.
  • If it is, then mark it by putting a x between the square bracket like so: [x]

NOTE: Only [x] is supported so if you have put any other letter or symbol between the brackets, that will be marked as invalid. If that is the case then please open a new pull request with the appropriate changes.

@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