Get the best out of our app
GeeksforGeeks App
Open App
Browser
Continue

Length of all prefixes that are also the suffixes of given string

Given a string S consisting of N characters, the task is to find the length of all prefixes of the given string S that are also suffixes of the same string S.

Examples:

Input: S = “ababababab”
Output: 2 4 6 8
Explanation:
The prefixes of S that are also its suffixes are:

1. “ab” of length = 2
2. “abab” of length = 4
3. “ababab” of length = 6
4. “abababab” of length = 8

Input: S = “geeksforgeeks”
Output: 5

Naive Approach: The simplest approach to solve the given problem is by using hashing to store the prefixes of the given string. Then, iterate through all the suffixes and check if they are present in the hash map or not. Follow the steps below to solve the problem:

• Initialize two deques, say prefix and suffix to store the prefix string and suffix strings of S.
• Initialize a HashMap, say M to store all the prefixes of S.
• Traverse the given string S over the range [0, N – 2] using the variable i
• Push the current character at the back of prefix and suffix deque.
• Mark prefix as true in the HashMap M.
• After the loop, add the last character of the string, say S[N – 1] to the suffix.
• Iterate over the range [0, N – 2] and perform the following steps:
• Remove the front character of the suffix.
• Now, check if the current deque is present in the HashMap M or not. If found to be true, then print the size of the deque.

Below is the implementation of the above approach:

C++14

```// C++ program for the above approach

#include <bits/stdc++.h>
using namespace std;

// Function to  find the length of all
// prefixes of the  given string that
// are also suffixes of the same string
void countSamePrefixSuffix(string s, int n)
{
// Stores the prefixes of the string
unordered_map<deque<char>, int> cnt;

// Stores the prefix & suffix strings
deque<char> prefix, suffix;

// Iterate in the range [0, n - 2]
for (int i = 0; i < n - 1; i++) {

// Add the current character to
// the prefix and suffix strings
prefix.push_back(s[i]);
suffix.push_back(s[i]);

// Mark the prefix as 1 in
// the HashMap
cnt[prefix] = 1;
}

// Add the last character to
// the suffix
suffix.push_back(s[n - 1]);
int index = n - 1;

// Iterate in the range [0, n - 2]
for (int i = 0; i < n - 1; i++) {

// Remove the character from
// the front of suffix deque
// to get the suffix string
suffix.pop_front();

// Check if the suffix is
// present in HashMap or not
if (cnt[suffix] == 1) {
cout << index << " ";
}

index--;
}
}

// Driver Code
int main()
{
string S = "ababababab";
int N = S.size();
countSamePrefixSuffix(S, N);

return 0;
}
```

Java

```// Java program for the above approach

import java.io.*;
import java.util.*;

class GFG {

public static void countSamePrefixSuffix(String s,
int n)
{
// Stores the prefixes of the string
HashMap<String, Integer> cnt = new HashMap<>();

// Iterate in the range [0, n - 2]
for (int i = 0; i < n - 1; i++) {
String prefix = s.substring(0, i + 1);
// Mark the prefix as 1 in
// the dictionary
cnt.put(prefix, 1);
}

int index = n;

// Iterate in the range [0, n - 2]
for (int i = 0; i < n - 1; i++) {
String suffix = s.substring(i);

// Check if the suffix is
// present in dictionary or not
if (cnt.containsKey(suffix)) {
System.out.print(index + " ");
}
index--;
}
}

public static void main(String[] args)
{
String s = "ababababab";
int n = s.length();
countSamePrefixSuffix(s, n);
}
}

// This code is contributed by lokesh.```

Python3

```# Python3 code to implement the approach

# Function to find the length of all
# prefixes of the given string that
# are also suffixes of the same string
def count_same_prefix_suffix(s: str, n: int) -> None:
# Stores the prefixes of the string
cnt = {}

# Stores the prefix & suffix strings
prefix, suffix = [], []

# Iterate in the range [0, n - 2]
for i in range(n - 1):
# Add the current character to
# the prefix and suffix strings
prefix.append(s[i])
suffix.append(s[i])

# Mark the prefix as 1 in
# the dictionary
cnt[str(prefix)] = 1

# Add the last character to
# the suffix
suffix.append(s[n - 1])
index = n - 1

# Iterate in the range [0, n - 2]
for i in range(n - 1):
# Remove the character from
# the front of suffix deque
# to get the suffix string
suffix.pop(0)

# Check if the suffix is
# present in dictionary or not
if cnt.get(str(suffix)) == 1:
print(index, end = " ")

index -= 1

S = 'ababababab'
N = len(S)
count_same_prefix_suffix(S, N)

# This code is contributed by phasing17```

C#

```// C# implementation of the above approach
using System;
using System.Collections.Generic;

public class GFG {

static void countSamePrefixSuffix(string s, int n)
{
// Stores the prefixes of the string
Dictionary<string, int> cnt
= new Dictionary<string, int>();

// Iterate in the range [0, n - 2]
for (int i = 0; i < n - 1; i++) {
string prefix = s.Substring(0, i + 1);
// Mark the prefix as 1 in the dictionary
cnt[prefix] = 1;
}

int index = n;

// Iterate in the range [0, n - 2]
for (int i = 0; i < n - 1; i++) {
string suffix = s.Substring(i);

// Check if the suffix is present in dictionary
// or not
if (cnt.ContainsKey(suffix)) {
Console.Write(index + " ");
}
index--;
}
}

static public void Main()
{

// Code
string s = "ababababab";
int n = s.Length;
countSamePrefixSuffix(s, n);
}
}

// This code is contributed by lokeshmvs21.```

Javascript

```function count_same_prefix_suffix(s, n) {
// Stores the prefixes of the string
let cnt = {};

// Stores the prefix & suffix strings
let prefix = [], suffix = [];

// Iterate in the range [0, n - 2]
for (let i = 0; i < n - 1; i++) {
// Add the current character to
// the prefix and suffix strings
prefix.push(s[i]);
suffix.push(s[i]);

// Mark the prefix as 1 in
// the dictionary
cnt[prefix.join("")] = 1;
}

// Add the last character to
// the suffix
suffix.push(s[n - 1]);
let index = n - 1;

// Iterate in the range [0, n - 2]
for (let i = 0; i < n - 1; i++) {
// Remove the character from
// the front of suffix deque
// to get the suffix string
suffix.shift();

// Check if the suffix is
// present in dictionary or not
if (cnt[suffix.join("")]) {
process.stdout.write(index + ' ');
}
index -= 1;
}
}

let S = 'ababababab'
let N = S.length
count_same_prefix_suffix(S, N)

// This code is contributed by phasing17
```
Output:

`8 6 4 2`

Time Complexity: O(N * N), where N is the length of the given string.
Auxiliary Space: O(N),  for storing all the prefix strings of length [1, 2, …., N – 2, N – 1] in the HashMap.

Better Approach: The above approach can also be optimized by using traverse the given string, S from the start, and in each iteration add the current character to the prefix string, and check if the prefix string is the same as the suffix of the same length or not. If found to be true, then print the length of the prefix string. Otherwise, check for the next prefix.

Below is the implementation of the above approach:

C++14

```// C++ program for the above approach

#include <bits/stdc++.h>
using namespace std;

// Function to  find the length of all
// prefixes of the given string that
// are also suffixes of the same string
void countSamePrefixSuffix(string s, int n)
{
// Stores the prefix string
string prefix = "";

// Traverse the string S
for (int i = 0; i < n - 1; i++) {

// Add the current character
// to the prefix string
prefix += s[i];

// Store the suffix string
string suffix = s.substr(
n - 1 - i, n - 1);

// Check if both the strings
// are equal or not
if (prefix == suffix) {
cout << prefix.size() << " ";
}
}
}

// Driver Code
int main()
{
string S = "ababababab";
int N = S.size();
countSamePrefixSuffix(S, N);

return 0;
}
```

Java

```// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;

class GFG {

// Function to  find the length of all
// prefixes of the given string that
// are also suffixes of the same string
static void countSamePrefixSuffix(String s, int n)
{

// Stores the prefix string
String prefix = "";

// Traverse the string S
for (int i = 0; i < n - 1; i++) {

// Add the current character
// to the prefix string
prefix += s.charAt(i);

// Store the suffix string
String suffix = s.substring(n - 1 - i, n);

// Check if both the strings
// are equal or not
if (prefix.equals(suffix)) {
System.out.print(prefix.length() + " ");
}
}
}

// Driver Code
public static void main(String[] args)
{
String S = "ababababab";
int N = S.length();

countSamePrefixSuffix(S, N);
}
}

// This code is contributed by Kingash```

Python3

```# Python3 program for the above approach

# Function to  find the length of all
# prefixes of the given that
# are also suffixes of the same string
def countSamePrefixSuffix(s, n):

# Stores the prefix string
prefix = ""

# Traverse the S
for i in range(n - 1):

# Add the current character
# to the prefix string
prefix += s[i]

# Store the suffix string
suffix = s[n - 1 - i: 2 * n - 2 - i]

# Check if both the strings
# are equal or not
if (prefix == suffix):
print(len(prefix), end = " ")

# Driver Code
if __name__ == '__main__':

S = "ababababab"
N = len(S)

countSamePrefixSuffix(S, N)

# This code is contributed by mohit kumar 29```

C#

```// C# program for the above approach
using System;
using System.Collections.Generic;

class GFG {

// Function to  find the length of all
// prefixes of the given string that
// are also suffixes of the same string
static void countSamePrefixSuffix(string s, int n)
{
// Stores the prefix string
string prefix = "";

// Traverse the string S
for (int i = 0; i < n - 1; i++) {

// Add the current character
// to the prefix string
prefix += s[i];

// Store the suffix string
string suffix = s.Substring(n - 1 - i, i + 1);

// Check if both the strings
// are equal or not
if (prefix == suffix) {
Console.Write(prefix.Length + " ");
}
}
}

// Driver Code
public static void Main()
{
string S = "ababababab";
int N = S.Length;
countSamePrefixSuffix(S, N);
}
}

// This code is contributed by SURENDRA_GANGWAR.```

Javascript

```<script>

// JavaScript program for the above approach

// Function to find the length of all
// prefixes of the given string that
// are also suffixes of the same string
function countSamePrefixSuffix( s,  n)
{

// Stores the prefix string
var prefix = "";

// Traverse the string S
for(let i = 0; i < n - 1; i++)
{

// Add the current character
// to the prefix string
prefix += s.charAt(i);

// Store the suffix string
var suffix = s.substring(n - 1 - i, n);

// Check if both the strings
// are equal or not
if (prefix==suffix)
{
document.write(prefix.length + " ");
}
}
}

// Driver Code

let S = "ababababab";
let N = S.length;

countSamePrefixSuffix(S, N);

</script>```
Output:

`2 4 6 8`

Time Complexity: O(N2)
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up