Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions String/ZFunction.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Author: Adrito Mukherjee
* Implementation of ZFunction in JavaScript
* ZFunction at an index i gives the length of the longest substring starting at i, that is also a prefix of the whole string
* ZFunction for all indices in a string can be calculated in O(N)
* Explanation: https://cp-algorithms.com/string/z-function.html
*/

function ZFunction (text) {
const length = text.length
const ZArray = Array(length).fill(0)
let left = 0
let right = 0
for (let index = 0; index < length; index++) {
if (index <= right) {
ZArray[index] = Math.min(right - index + 1, ZArray[index - left])
}
while (
index + ZArray[index] < length &&
text[ZArray[index]] === text[index + ZArray[index]]
) {
ZArray[index]++
}
if (index + ZArray[index] - 1 > right) {
left = index
right = index + ZArray[index] - 1
}
}
return ZArray
}

export default ZFunction
15 changes: 15 additions & 0 deletions String/test/ZFunction.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import ZFunction from '../ZFunction'

test('Test Case 1', () => {
const text = 'aabxaayaab'
const ZArray = ZFunction(text)
expect(ZArray).toEqual([10, 1, 0, 0, 2, 1, 0, 3, 1, 0])
})

test('Test Case 2', () => {
const text = 'aabxaabxcaabxaabxay'
const ZArray = ZFunction(text)
expect(ZArray).toEqual([
19, 1, 0, 0, 4, 1, 0, 0, 0, 8, 1, 0, 0, 5, 1, 0, 0, 1, 0
])
})