I can't find Z function implementation here so I will write that. There is a link of an algorithm below. Z funciton: https://www.geeksforgeeks.org/z-algorithm-linear-time-pattern-searching-algorithm/