Data Structures & AlgorithmsHardGATE CS · DSA
Z-array: z[i] is the length of the longest common prefix of s and s[i:], with z[0] defined as 0. What is printed?
Z-array: z[i] is the length of the longest common prefix of s and s[i:], with z[0] defined as 0. What is printed?
s = "abaabaaba"
z = [0] * len(s)
for i in range(1, len(s)):
while i + z[i] < len(s) and s[z[i]] == s[i + z[i]]: z[i] += 1
print(z, sum(z))- A. [0, 0, 1, 6, 0, 1, 3, 1, 0] 12
- B. [0, 1, 0, 6, 0, 1, 3, 0, 1] 12
- C. [0, 0, 1, 6, 0, 1, 3, 0, 1] 12
- D. [0, 0, 1, 6, 0, 1, 3, 0, 1] 6
Correct answer: C. [0, 0, 1, 6, 0, 1, 3, 0, 1] 12
Each z[i] counts how far s[i:] agrees with the start of s. Output: [0, 0, 1, 6, 0, 1, 3, 0, 1] 12.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Kadane's algorithm is applied to an array whose elements are ALL negative, using the version cur = max(x, cur + x), best = max(best, cur)…
- Remove the n-th node from the END of a linked list in one pass, using a dummy node and a gap of n between two pointers. What is printed?…
- Z-array: z[i] is the length of the longest common prefix of s and s[i:], with z[0] defined as 0. What is printed? python s = "bbaaaabab" z…
- Asteroids move along a line: positive values move right, negative move left; on collision the smaller (by absolute value) explodes, equal…
- A difference array is used for q range-increment updates followed by one final read of all n values. What is the total time?
- Top-down merge sort (split at mid = n // 2, recurse, then merge, stopping comparisons when one side runs out) sorts [10, 29, 19, 28, 32…