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 = "bbaaaabab"
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, 1, 0, 0, 0, 0, 1, 0, 1] 1
- B. [0, 1, 0, 0, 0, 0, 1, 0, 1] 3
- C. [0, 1, 0, 0, 0, 0, 0, 1, 1] 3
- D. [1, 0, 0, 0, 0, 0, 1, 0, 1] 3
Correct answer: B. [0, 1, 0, 0, 0, 0, 1, 0, 1] 3
Each z[i] counts how far s[i:] agrees with the start of s. Output: [0, 1, 0, 0, 0, 0, 1, 0, 1] 3.
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
- 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…
- The Boyer–Moore majority vote (candidate/counter, no verification pass) runs on [3, 3, 3, 3, 7, 3, 7, 5, 5]. What candidate and final…
- A prefix-sum array P of A (P[0] = 0, P[i] = A[0] + … + A[i − 1]) is built. Which expression gives the sum A[l] + … + A[r] (0-based…
- A peak is an element larger than its neighbours (array ends count as −∞). Binary search runs on [16, 19, 40, 1, 18, 30, 54, 59, 45]: while…