Length of all prefixes that are also the suffixes of given string
Last Updated :
23 Jan, 2023
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
// 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
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>
Time Complexity: O(N2)
Auxiliary Space: O(N)
Similar Reads
Print the longest prefix of the given string which is also the suffix of the same string Given string str, the task is to find the longest prefix which is also the suffix of the given string. The prefix and suffix should not overlap. If no such prefix exists then print -1. Examples: Input: str = "aabcdaabc" Output: aabc The string "aabc" is the longest prefix which is also suffix. Input
8 min read
Count of strings whose prefix match with the given string to a given length k Given an array of strings arr[] and given some queries where each query consists of a string str and an integer k. The task is to find the count of strings in arr[] whose prefix of length k matches with the k length prefix of str.Examples: Input: arr[] = {"abba", "abbb", "abbc", "abbd", "abaa", "abc
15+ min read
Find the Longest Non-Prefix-Suffix Substring in the Given String Given a string s of length n. The task is to determine the longest substring t such that t is neither the prefix nor the suffix of string s, and that substring must appear as both prefix and suffix of the string s. If no such string exists, print -1. Example: Input: s = "fixprefixsuffix"Output: fix
7 min read
Sub-strings of a string that are prefix of the same string Given a string str, the task is to count all possible sub-strings of the given string that are prefix of the same string. Examples: Input: str = "ababc" Output: 7 All possible sub-string are "a", "ab", "aba", "abab", "ababc", "a" and "ab" Input: str = "abdabc" Output: 8 Approach: Traverse the string
10 min read
Minimum count of prefixes and suffixes of a string required to form given string Given two strings str1 and str2, the task is to find the minimum number of prefixes and suffixes of str2 required to form the string str1. If the task is not possible, return "-1".Example: Input: str1 = "HELLOWORLD", str2 = "OWORLDHELL"Output: 2Explanation: The above string can be formed as "HELL" +
10 min read
Find the Suffix Array of given String with no repeating character Given a string str of size N, the task is to find the suffix array of the given string. Note: A suffix array is a sorted array of all suffixes of a given string. Examples: Input: str = "prince"Output: 4 5 2 3 0 1Explanation: The suffixes are0 prince 4 ce1 rince Sort the suffixes 5 e 2 ince ---------
6 min read