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:
- “ab” of length = 2
- “abab” of length = 4
- “ababab” of length = 6
- “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
#include <bits/stdc++.h>
using namespace std;
void countSamePrefixSuffix(string s, int n)
{
unordered_map<deque< char >, int > cnt;
deque< char > prefix, suffix;
for ( int i = 0; i < n - 1; i++) {
prefix.push_back(s[i]);
suffix.push_back(s[i]);
cnt[prefix] = 1;
}
suffix.push_back(s[n - 1]);
int index = n - 1;
for ( int i = 0; i < n - 1; i++) {
suffix.pop_front();
if (cnt[suffix] == 1) {
cout << index << " " ;
}
index--;
}
}
int main()
{
string S = "ababababab" ;
int N = S.size();
countSamePrefixSuffix(S, N);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
public static void countSamePrefixSuffix(String s,
int n)
{
HashMap<String, Integer> cnt = new HashMap<>();
for ( int i = 0 ; i < n - 1 ; i++) {
String prefix = s.substring( 0 , i + 1 );
cnt.put(prefix, 1 );
}
int index = n;
for ( int i = 0 ; i < n - 1 ; i++) {
String suffix = s.substring(i);
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);
}
}
|
Python3
def count_same_prefix_suffix(s: str , n: int ) - > None :
cnt = {}
prefix, suffix = [], []
for i in range (n - 1 ):
prefix.append(s[i])
suffix.append(s[i])
cnt[ str (prefix)] = 1
suffix.append(s[n - 1 ])
index = n - 1
for i in range (n - 1 ):
suffix.pop( 0 )
if cnt.get( str (suffix)) = = 1 :
print (index, end = " " )
index - = 1
S = 'ababababab'
N = len (S)
count_same_prefix_suffix(S, N)
|
C#
using System;
using System.Collections.Generic;
public class GFG {
static void countSamePrefixSuffix( string s, int n)
{
Dictionary< string , int > cnt
= new Dictionary< string , int >();
for ( int i = 0; i < n - 1; i++) {
string prefix = s.Substring(0, i + 1);
cnt[prefix] = 1;
}
int index = n;
for ( int i = 0; i < n - 1; i++) {
string suffix = s.Substring(i);
if (cnt.ContainsKey(suffix)) {
Console.Write(index + " " );
}
index--;
}
}
static public void Main()
{
string s = "ababababab" ;
int n = s.Length;
countSamePrefixSuffix(s, n);
}
}
|
Javascript
function count_same_prefix_suffix(s, n) {
let cnt = {};
let prefix = [], suffix = [];
for (let i = 0; i < n - 1; i++) {
prefix.push(s[i]);
suffix.push(s[i]);
cnt[prefix.join( "" )] = 1;
}
suffix.push(s[n - 1]);
let index = n - 1;
for (let i = 0; i < n - 1; i++) {
suffix.shift();
if (cnt[suffix.join( "" )]) {
process.stdout.write(index + ' ' );
}
index -= 1;
}
}
let S = 'ababababab'
let N = S.length
count_same_prefix_suffix(S, N)
|
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
#include <bits/stdc++.h>
using namespace std;
void countSamePrefixSuffix(string s, int n)
{
string prefix = "" ;
for ( int i = 0; i < n - 1; i++) {
prefix += s[i];
string suffix = s.substr(
n - 1 - i, n - 1);
if (prefix == suffix) {
cout << prefix.size() << " " ;
}
}
}
int main()
{
string S = "ababababab" ;
int N = S.size();
countSamePrefixSuffix(S, N);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
static void countSamePrefixSuffix(String s, int n)
{
String prefix = "" ;
for ( int i = 0 ; i < n - 1 ; i++) {
prefix += s.charAt(i);
String suffix = s.substring(n - 1 - i, n);
if (prefix.equals(suffix)) {
System.out.print(prefix.length() + " " );
}
}
}
public static void main(String[] args)
{
String S = "ababababab" ;
int N = S.length();
countSamePrefixSuffix(S, N);
}
}
|
Python3
def countSamePrefixSuffix(s, n):
prefix = ""
for i in range (n - 1 ):
prefix + = s[i]
suffix = s[n - 1 - i: 2 * n - 2 - i]
if (prefix = = suffix):
print ( len (prefix), end = " " )
if __name__ = = '__main__' :
S = "ababababab"
N = len (S)
countSamePrefixSuffix(S, N)
|
C#
using System;
using System.Collections.Generic;
class GFG {
static void countSamePrefixSuffix( string s, int n)
{
string prefix = "" ;
for ( int i = 0; i < n - 1; i++) {
prefix += s[i];
string suffix = s.Substring(n - 1 - i, i + 1);
if (prefix == suffix) {
Console.Write(prefix.Length + " " );
}
}
}
public static void Main()
{
string S = "ababababab" ;
int N = S.Length;
countSamePrefixSuffix(S, N);
}
}
|
Javascript
<script>
function countSamePrefixSuffix( s, n)
{
var prefix = "" ;
for (let i = 0; i < n - 1; i++)
{
prefix += s.charAt(i);
var suffix = s.substring(n - 1 - i, n);
if (prefix==suffix)
{
document.write(prefix.length + " " );
}
}
}
let S = "ababababab" ;
let N = S.length;
countSamePrefixSuffix(S, N);
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(N)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
23 Jan, 2023
Like Article
Save Article