Data Structures & AlgorithmsVery hardProduct company OA
Z-array (z[i] = length of the longest common prefix of s and s[i:]). What is printed?
Z-array (z[i] = length of the longest common prefix of s and s[i:]). What is printed?
def z(s):
n = len(s); z = [0] * n; l = r = 0
for i in range(1, n):
if i < r: z[i] = min(r - i, z[i - l])
while i + z[i] < n and s[z[i]] == s[i + z[i]]: z[i] += 1
if i + z[i] > r: l, r = i, i + z[i]
return z
s = "aabcaabxaab"
zz = z(s)
print(zz, sum(1 for i in range(1, len(s)) if zz[i] >= 3))- A. [0, 1, 0, 0, 3, 1, 0, 0, 2, 1, 0] 2
- B. [0, 1, 0, 0, 4, 1, 0, 0, 3, 1, 0] 3
- C. [0, 1, 0, 0, 3, 1, 0, 0, 3, 1, 0] 2
- D. [0, 1, 0, 0, 3, 1, 0, 0, 3, 1, 0] 3
Correct answer: C. [0, 1, 0, 0, 3, 1, 0, 0, 3, 1, 0] 2
s = aabcaabxaab. Position 4 starts 'aabx…' which matches 'aabc' for 3 characters; position 8 starts 'aab' and the string ends, so 3. Inside the box [l, r) the algorithm copies z[i − l] capped at r − i, which is what keeps it O(n). Exactly two positions (4 and 8) have z ≥ 3, i.e. two occurrences of the 3-character prefix 'aab' after the start. z[0] is conventionally 0 (or n).
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
- Rabin–Karp over digits with base 10 and a deliberately tiny modulus 7. It returns (true matches, spurious hash hits). What is printed?…
- Open addressing with linear probing (size 7, h(k) = k mod 7). Deletion leaves a tombstone 'X'; insert reuses the first tombstone; find…
- Largest rectangle under a histogram using a stack of (start index, height). What is printed? python def rect(h): st, best = [], 0 for i, x…
- Rain water trapped between bars, computed with two pointers. What is printed? python def water(h): l, r, lm, rm, w = 0, len(h) - 1, 0, 0…
- Next greater element in a CIRCULAR array (scan the array twice, pushing indices only in the first pass). What is printed? python def…
- Towers stand in a row. Two towers can see each other if every tower strictly between them is shorter than both. The function counts such…