Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Print the longest prefix of the given string which is also the suffix of the same string
Next article icon

Remove longest prefix of the String which has duplicate substring

Last Updated : 12 Apr, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string S of length N, the task is to remove the longest prefix of the string which has at least one duplicate substring present in S.

Note: The duplicate substring cannot be the prefix itself

Examples: 

Input: S = "GeeksforGeeks"
Output: "forGeeks"
Explanation: The longest substring which has a duplicate is "Geeks".
After deleting this the remaining string becomes "forGeeks".

Input: S = "aaaaa"
Output: "a"
Explanation: Here the longest prefix which has a duplicate substring is "aaaa".
So after deleting this the remaining string is "a". 
Note that the whole string is not selected because then the duplicate string is the prefix itself.

 

Approach: The problem can be solved based on the following idea:

Find all the characters which can be a starting point of a substring which is a duplicate of the prefix. Then from these points find the duplicate of the longest prefix and delete that prefix.

Follow the illustration below for a better understanding

Illustration:

For example take S = "aaaaa"

The possible starting points can be at indices 1, 2, 3, 4.

For index 1: The possible duplicate of the prefix is "aaaa".
It has length = 4

For index 2: The possible duplicate of the prefix is "aaa".
It has length = 3

For index 3: The possible duplicate of the prefix is "aa".
It has length = 2

For index 4: The possible duplicate of the prefix is "a".
It has length = 1

So remove the prefix of length 4. Therefore the string becomes "a"

Follow the approach mentioned below to solve the problem:

  • Use two pointers: one to the start of the prefix (say i which is 0 initially) and the other (say j)to find the starting point of all possible duplicate substrings.
  • Iterate j from 1 to N:
    • If S[j] matches S[i] then use a pointer (say k) and iterate both i and k to find the length of the substring starting from j which is duplicate of the prefix.
    • Update the maximum length.
    • Set i again to 0.
  • Delete the maximum length prefix.

Below is the implementation of the above approach:

C++
// C++ code for the above approach:  #include <bits/stdc++.h> using namespace std;  // Function to delete the longest prefix string delPrefix(string S) {     if (S.size() == 1)         return S;     int i = 0, maxi = 0;      // Loop to find the     // longest duplicate of prefix     for (int j = 1; j < S.size(); j++) {         int k = j;         while (k < S.size() and S[k] == S[i]) {             k++;             i++;         }         maxi = max(maxi, i);         i = 0;     }     return S.substr(maxi); }  // Driver code int main() {     string S = "aaaaa";     string ans = delPrefix(S);      // Function call     cout << ans;     return 0; } 
Java
// Java code for the above approach import java.io.*;  class GFG  {      // Function to delete the longest prefix   public static String delPrefix(String S)   {     if (S.length() == 1)       return S;     int i = 0, maxi = 0;      // Loop to find the     // longest duplicate of prefix     for (int j = 1; j < S.length(); j++) {       int k = j;       while (k < S.length()              && S.charAt(k) == S.charAt(i)) {         k++;         i++;       }       maxi = Math.max(maxi, i);       i = 0;     }     return S.substring(maxi);   }   public static void main(String[] args)   {     String S = "aaaaa";     String ans = delPrefix(S);      // Function call     System.out.print(ans);   } }  // This code is contributed by Rohit Pradhan 
Python3
# Python code for the above approach:  # Function to delete the longest prefix def delPrefix(S):      if (len(S) == 1):         return S     i = 0     maxi = 0      # Loop to find the     # longest duplicate of prefix     for j in (1, len(S)+1):         k = j         while (k < len(S) and S[k] == S[i]):             k = k + 1             i = i + 1          maxi = max(maxi, i)         i = 0      return S[maxi:]  # Driver code S = "aaaaa" ans = delPrefix(S)  # Function call print(ans)  # This code is contributed by Taranpreet 
C#
// C# code for the above approach using System;  public class GFG{    // Function to delete the longest prefix   public static string delPrefix(string S)   {     if (S.Length == 1)       return S;     int i = 0, maxi = 0;      // Loop to find the     // longest duplicate of prefix     for (int j = 1; j < S.Length; j++) {       int k = j;       while (k < S.Length              && S[k] == S[i]) {         k++;         i++;       }       maxi = Math.Max(maxi, i);       i = 0;     }     return S.Substring(maxi);   }    static public void Main (){      string S = "aaaaa";     string ans = delPrefix(S);      // Function call     Console.Write(ans);   } }  // This code is contributed by hrithikgarg03188. 
JavaScript
 <script>         // JavaScript code for the above approach         function delPrefix(S) {             if (S.length == 1)                 return S;             let i = 0, maxi = 0;              // Loop to find the             // longest duplicate of prefix             for (let j = 1; j < S.length; j++) {                 let k = j;                 while (k < S.length && S[k] == S[i]) {                     k++;                     i++;                 }                 maxi = Math.max(maxi, i);                 i = 0;             }             return S.slice(maxi);         }          // Driver code         let S = "aaaaa";         let ans = delPrefix(S);          // Function call         document.write(ans)              // This code is contributed by Potta Lokesh     </script> 

Output
a

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


Next Article
Print the longest prefix of the given string which is also the suffix of the same string
author
mayank007rawa
Improve
Article Tags :
  • Strings
  • Greedy
  • DSA
  • String Duplicates
  • prefix
  • substring
Practice Tags :
  • Greedy
  • Strings

Similar Reads

  • Largest substring of str2 which is a prefix of str1
    Given two string str1 and str2, the task is to find the longest prefix of str1 which is present as a substring of the string str2. Print the prefix if possible else print -1.Examples: Input: str1 = "geeksfor", str2 = "forgeeks" Output: geeks All the prefixes of str1 which are present in str2 are "g"
    5 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
  • Print Longest substring without repeating characters
    Given a string s having lowercase characters, find the length of the longest substring without repeating characters. Examples: Input: s = “geeksforgeeks”Output: 7 Explanation: The longest substrings without repeating characters are “eksforg” and “ksforge”, with lengths of 7. Input: s = “aaa”Output:
    14 min read
  • 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
  • Find the longest sub-string which is prefix, suffix and also present inside the string
    Given string str. The task is to find the longest sub-string which is a prefix, a suffix, and a sub-string of the given string, str. If no such string exists then print -1.Examples: Input: str = "fixprefixsuffix" Output: fix "fix" is a prefix, suffix and present inside in the string too.Input: str =
    10 min read
  • Encode given string by replacing substrings with prefix same as itself with *
    Given string str of size N containing only lowercase English letters. The task is to encrypt the string such that the substrings having same prefix as itself are replaced by a *. Generate the encrypted string. Note: If the string can be encrypted in multiple ways, find the smallest encrypted string.
    9 min read
  • Longest Substring Without Repeating Characters
    Given a string s having lowercase characters, find the length of the longest substring without repeating characters. Examples: Input: s = "geeksforgeeks"Output: 7 Explanation: The longest substrings without repeating characters are "eksforg” and "ksforge", with lengths of 7. Input: s = "aaa"Output:
    12 min read
  • Find the longest sub-string which is prefix, suffix and also present inside the string | Set 2
    Given string str. The task is to find the longest sub-string which is a prefix, a suffix and a sub-string of the given string, str. If no such string exists then print -1.Examples: Input: str = "geeksisforgeeksinplatformgeeks" Output: geeksInput: str = “fixprefixsuffix” Output: fix Note: The Set-1 o
    9 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
  • Javascript Program To Find Length Of The Longest Substring Without Repeating Characters
    Given a string str, find the length of the longest substring without repeating characters.  For “ABDEFGABEF”, the longest substring are “BDEFGA” and "DEFGAB", with length 6.For “BBBB” the longest substring is “B”, with length 1.For "GEEKSFORGEEKS", there are two longest substrings shown in the below
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences