VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-finding-borders/

⇱ CSES Solutions – Finding Borders - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions – Finding Borders

Last Updated : 23 Jul, 2025

A border of a string S is a prefix that is also a suffix of the string but not the whole string. For example, the borders of "abcababcab" are "ab" and "abcab"

Your task is to find all border lengths of a given string.

Examples:

Input: S="abcababcab"
Output: 2 5
Explanation: The string “abcababcab” has two borders: “ab” and “abcab”. “ab” is a prefix of the string (the first two characters) and also a suffix (the last two characters). Its length is 2. “abcab” is also a prefix (the first five characters) and a suffix (the last five characters). Its length is 5.

Input: S="aaabbbbbba"
Output: 1
Explanation: The string “aaabbbbbba” has one border: “a”. “a” is a prefix of the string (the first character) and also a suffix (the last character). Its length is 1.

Approach: To solve the problem, follow the below idea:

We can solve this problem with String comparison using Rolling Hash.

We will compute the hash value of the prefix and suffix strings and if the hash value of both the string is same that means our prefix string and suffix strings are same then print the length of the string.

: We calculate the prefix hash from left to right and the suffix hash from right to left. We use two different prime numbers p1 and p2 to calculate two different hashes for each prefix and suffix. This reduces the probability of hash collisions.

: For each position i in the string (from 0 to N-2), we compare the prefix hash and the suffix hash. If they are equal, it means that the prefix and suffix are the same, so we print the length of the border (i+1).

: To avoid overflow and make the hash comparison more efficient, we perform all the calculations under a large prime number MOD.

: To make the power calculations more efficient, we precompute the powers of p1 and p2 under MOD.

Step-by-step algorithm:

  • Define the prime values p1, p2 and MOD then precompute the power array for hash value calculation.
  • Now iterate in the string from [0...N-2] and calculate hash value of prefix and suffix strings.
  • if values are same that means our strings are same so we print the length of the string and move to the next iteration.

Below is the implementation of algorithm:


Output
2 5 

Time Complexity: O(N), where N is the length of string S.
Auxiliary Space: O(N)

Comment
Article Tags: