Longest prefix which is also suffix - GeeksforGeeks

CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses
For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more
School Guide
Python Programming
Learn To Make Apps
Explore more
All Courses
TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms
Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data ScienceMachine LearningData Science
Machine Learning
Data Science
CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software DesignsSoftware Design PatternsSystem Design Tutorial
Software Design Patterns
System Design Tutorial
School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
School Programming
MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
JobsApply for JobsPost a JobJOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems




WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri
Geeks Digest
Quizzes
Geeks Campus
Gblog Articles
IDE
Campus Mantri
Sign In
Sign In
Home
Saved Videos
Courses


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps

Explore more


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


ML & Data Science
                        


Machine Learning

Data Science


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


School Learning
                        


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Student Chapter

Geek on the Top

Internship

Careers


Curated DSA Lists
                        


Top 50 Array Problems

Top 50 String Problems

Top 50 Tree Problems

Top 50 Graph Problems

Top 50 DP Problems


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


Practice
                        


All DSA Problems

Problem of the Day

Interview Series: Weekly Contests

Bi-Wizard Coding: School Contests

Contests and Events

Practice SDE Sheet


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


DSA Live Classes


System Design


Java Backend Development


Full Stack LIVE


Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


DSA- Self Paced


SDE Theory


Must-Do Coding Questions


Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Competitive Programming


Data Structures with C++


Data Science


Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


DSA- Self Paced


CIP


JAVA / Python / C++


Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps

Explore more


School Guide


Python Programming


Learn To Make Apps


Explore more


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Searching Algorithms


Sorting Algorithms


Graph Algorithms


Pattern Searching


Geometric Algorithms


Mathematical


Bitwise Algorithms


Randomized Algorithms


Greedy Algorithms


Dynamic Programming


Divide and Conquer


Backtracking


Branch and Bound


All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Asymptotic Analysis


Worst, Average and Best Cases


Asymptotic Notations


Little o and little omega notations


Lower and Upper Bound Theory


Analysis of Loops


Solving Recurrences


Amortized Analysis


What does 'Space Complexity' mean ?


Pseudo-polynomial Algorithms


Polynomial Time Approximation Scheme


A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Arrays


Linked List


Stack


Queue


Binary Tree


Binary Search Tree


Heap


Hashing


Graph


Advanced Data Structure


Matrix


Strings


All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Company Preparation


Top Topics


Practice Company Questions


Interview Experiences


Experienced Interviews


Internship Interviews


Competititve Programming


Design Patterns


System Design Tutorial


Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


C


C++


Java


Python


C#


JavaScript


jQuery


SQL


PHP


Scala


Perl


Go Language


HTML


CSS


Kotlin


ML & Data Science
                        


Machine Learning

Data Science


Machine Learning


Data Science


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


Mathematics


Operating System


DBMS


Computer Networks


Computer Organization and Architecture


Theory of Computation


Compiler Design


Digital Logic


Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


GATE Computer Science Notes


Last Minute Notes


GATE CS Solved Papers


GATE CS Original Papers and Official Keys


GATE 2021 Dates


GATE CS 2021 Syllabus


Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


HTML


CSS


JavaScript


AngularJS


ReactJS


NodeJS


Bootstrap


jQuery


PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


Software Design Patterns


System Design Tutorial


School Learning
                        


School Programming


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Number System


Algebra


Trigonometry


Statistics


Probability


Geometry


Mensuration


Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


ISRO CS Original Papers and Official Keys


ISRO CS Solved Papers


ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


UGC NET CS Notes Paper II


UGC NET CS Notes Paper III


UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Student Chapter

Geek on the Top

Internship

Careers


Campus Ambassador Program


School Ambassador Program


Project


Geek of the Month


Campus Geek of the Month


Placement Course


Competititve Programming


Testimonials


Student Chapter


Geek on the Top


Internship


Careers


Curated DSA Lists
                        


Top 50 Array Problems

Top 50 String Problems

Top 50 Tree Problems

Top 50 Graph Problems

Top 50 DP Problems


Top 50 Array Problems


Top 50 String Problems


Top 50 Tree Problems


Top 50 Graph Problems


Top 50 DP Problems


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


Apply for Jobs


Post a Job


JOB-A-THON


Practice
                        


All DSA Problems

Problem of the Day

Interview Series: Weekly Contests

Bi-Wizard Coding: School Contests

Contests and Events

Practice SDE Sheet


All DSA Problems


Problem of the Day


Interview Series: Weekly Contests


Bi-Wizard Coding: School Contests


Contests and Events


Practice SDE Sheet

GBlog
Puzzles
What's New ?
Array
Matrix
Strings
Hashing
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Graph
Searching
Sorting
Divide & Conquer
Mathematical
Geometric
Bitwise
Greedy
Backtracking
Branch and Bound
Dynamic Programming
Pattern Searching
Randomized
Maximum length prefix of one string that occurs as subsequence in another
Longest prefix which is also suffix
Maximum occurring character in an input string | Set-2
Return maximum occurring character in an input string
Remove duplicates from a given string
Remove duplicates from a string in O(1) extra space
Minimum insertions to form a palindrome | DP-28
Minimum number of Appends needed to make a string palindrome
Minimum characters to be added at front to make string palindrome
KMP Algorithm for Pattern Searching
Rabin-Karp Algorithm for Pattern Searching
Naive algorithm for Pattern Searching
Optimized Algorithm for Pattern Searching
Finite Automata algorithm for Pattern Searching
Pattern Searching | Set 6 (Efficient Construction of Finite Automata)
Boyer Moore Algorithm for Pattern Searching
Boyer Moore Algorithm | Good Suffix heuristic
Aho-Corasick Algorithm for Pattern Searching
Z algorithm (Linear time pattern searching Algorithm)
Check if a string is substring of another
Given two strings, find if first string is a subsequence of second
Find number of times a string occurs as a subsequence in given string
Wildcard Pattern Matching
Search a Word in a 2D Grid of characters
Frequency of a substring in a string
Maximum length prefix of one string that occurs as subsequence in another
Longest prefix which is also suffix
Maximum occurring character in an input string | Set-2
Return maximum occurring character in an input string
Remove duplicates from a given string
Remove duplicates from a string in O(1) extra space
Minimum insertions to form a palindrome | DP-28
Minimum number of Appends needed to make a string palindrome
Minimum characters to be added at front to make string palindrome
KMP Algorithm for Pattern Searching
Rabin-Karp Algorithm for Pattern Searching
Naive algorithm for Pattern Searching
Optimized Algorithm for Pattern Searching
Finite Automata algorithm for Pattern Searching
Pattern Searching | Set 6 (Efficient Construction of Finite Automata)
Boyer Moore Algorithm for Pattern Searching
Boyer Moore Algorithm | Good Suffix heuristic
Aho-Corasick Algorithm for Pattern Searching
Z algorithm (Linear time pattern searching Algorithm)
Check if a string is substring of another
Given two strings, find if first string is a subsequence of second
Find number of times a string occurs as a subsequence in given string
Wildcard Pattern Matching
Search a Word in a 2D Grid of characters
Frequency of a substring in a string
Difficulty Level :
Hard
Given a string s, find the length of the longest prefix, which is also a suffix. The prefix and suffix should not overlap. 
Examples: 
Input : aabcdaabc
Output : 4
The string "aabc" is the longest
prefix which is also suffix.

Input : abcab
Output : 2

Input : aaaa
Output : 2
Simple Solution: Since overlapping prefixes and suffixes is not allowed, we break the string from the middle and start matching left and right strings. If they are equal return size of one string, else they try for shorter lengths on both sides.Below is a solution to the above approach!
C++
Java
Python3
C#
Javascript
// CPP program to find length of the// longest prefix which is also suffix#include <bits/stdc++.h>using namespace std; // Function to find largest prefix// which is also a suffixint largest_prefix_suffix(const std::string                                      &str){     int n = str.length();     // if n is less than 2  if(n < 2) {    return 0;  }   int len = 0;  int i = 1;     // Iterate i till n  while(i < n)  {         // If str[i] is equal to    // str[len]    if(str[i] == str[len])    {      ++len;      ++i;    }    else    {      i = i - len + 1;      len = 0;    }  }     // Return len  return len>n/2? len/2:len; } // Driver codeint main(){       string s = "blablabla";   // Function Call  cout << largest_prefix_suffix(s);  return 0;}
// Java program to find length of the longest// prefix which is also suffixclass GFG{        // Function to find largest prefix   // which is also a suffix   static int longestPrefixSuffix(String s)   {      int n = s.length();       // If n is less than 2      if(n < 2) {          return 0;      }       int len = 0;      int i = (n + 1)/2;       // Iterate i till n      while(i < n)      {         // If s.charAt(i) is equal to        // s.charAt(len)        if(s.charAt(i) == s.charAt(len))        {          ++len;          ++i;        }        else        {          i = i - len + 1;          len = 0;        }      }       // Return len      return len;   }         // Driver code  public static void main (String[] args)  {    String s = "abcaabc";    System.out.println(longestPrefixSuffix(s));  }} // This code is contributed by Anant Agarwal.
# Python3 program to find length# of the longest prefix which# is also suffixdef longestPrefixSuffix(s) :    n = len(s)         for res in range(n // 2, 0, -1) :                 # Check for shorter lengths        # of first half.        prefix = s[0: res]        suffix = s[n - res: n]                 if (prefix == suffix) :            return res                  # if no prefix and suffix match    # occurs    return 0     # Driver Codeif __name__ == "__main__":    s = "blablabla"    print(longestPrefixSuffix(s)) # This code is contributed by Nikita Tiwari.
// C# program to find length of the longest// prefix which is also suffixusing System; class GFG{         // Function to find largest prefix    // which is also a suffix    static int longestPrefixSuffix(String s)    {        int n = s.Length;             // if n is less than 2        if(n < 2) {          return 0;        }         int len = 0;        int i = (n + 1)/2;         // Iterate i till n        while(i < n)        {           // If str[i] is equal to          // str[len]          if(str[i] == str[len])          {            ++len;            ++i;          }          else          {            i = i - len + 1;            len = 0;          }        }         // Return len        return len;    }         // Driver code    public static void Main ()    {        String s = "blablabla";                 Console.WriteLine(longestPrefixSuffix(s));    }} // This code is contributed by vt_m.
<script> // JavaScript program to find length of the longest// prefix which is also suffix    // Function to find largest prefix   // which is also a suffix   function longestPrefixSuffix(s)   {      var n = s.length;       // If n is less than 2      if(n < 2) {          return 0;      }       var len = 0;      var i = (n + 1)/2;       // Iterate i till n      while(i < n)      {         // If s[i] is equal to        // s[len]        if(s[i] == s[len])        {          ++len;          ++i;        }        else        {          i = i - len + 1;          len = 0;        }      }       // Return len      return len;   }     // Driver codevar s = "blablabla";document.write(longestPrefixSuffix(s)); // This code contributed by shikhasingrajput </script>
3
 
Efficient Solution: The idea is to use the preprocessing algorithm KMP search. In the preprocessing algorithm, we build lps array which stores the following values.
lps[i] = the longest proper prefix of pat[0..i] which is also a suffix of pat[0..i].
C++
Java
Python3
C#
PHP
Javascript
// Efficient CPP program to find length of// the longest prefix which is also suffix#include<bits/stdc++.h>using namespace std; // Returns length of the longest prefix// which is also suffix and the two do// not overlap. This function mainly is// copy computeLPSArray() of in below post// https://www.geeksforgeeks.org/searching-for-patterns-set-2-kmp-algorithm/int longestPrefixSuffix(string s){    int n = s.length();     int lps[n];    lps[0] = 0; // lps[0] is always 0     // length of the previous    // longest prefix suffix    int len = 0;     // the loop calculates lps[i]    // for i = 1 to n-1    int i = 1;    while (i < n)    {        if (s[i] == s[len])        {            len++;            lps[i] = len;            i++;        }        else // (pat[i] != pat[len])        {            // This is tricky. Consider            // the example. AAACAAAA            // and i = 7. The idea is            // similar to search step.            if (len != 0)            {                len = lps[len-1];                 // Also, note that we do                // not increment i here            }            else // if (len == 0)            {                lps[i] = 0;                i++;            }        }    }     int res = lps[n-1];     // Since we are looking for    // non overlapping parts.    return (res > n/2)? res/2 : res;} // Driver program to test above functionint main(){    string s = "abcab";    cout << longestPrefixSuffix(s);    return 0;}
// Efficient Java program to find length of// the longest prefix which is also suffix class GFG{    // Returns length of the longest prefix    // which is also suffix and the two do    // not overlap. This function mainly is    // copy computeLPSArray() of in below post    // https://www.geeksforgeeks.org/searching-    // for-patterns-set-2-kmp-algorithm/    static int longestPrefixSuffix(String s)    {        int n = s.length();             int lps[] = new int[n];                 // lps[0] is always 0        lps[0] = 0;             // length of the previous        // longest prefix suffix        int len = 0;             // the loop calculates lps[i]        // for i = 1 to n-1        int i = 1;        while (i < n)        {            if (s.charAt(i) == s.charAt(len))            {                len++;                lps[i] = len;                i++;            }                          // (pat[i] != pat[len])            else            {                // This is tricky. Consider                // the example. AAACAAAA                // and i = 7. The idea is                // similar to search step.                if (len != 0)                {                    len = lps[len-1];                         // Also, note that we do                    // not increment i here                }                                 // if (len == 0)                else                {                    lps[i] = 0;                    i++;                }            }        }             int res = lps[n-1];             // Since we are looking for        // non overlapping parts.        return (res > n/2)? n/2 : res;    }         // Driver program    public static void main (String[] args)    {        String s = "abcab";        System.out.println(longestPrefixSuffix(s));    }} // This code is contributed by Anant Agarwal.
# Efficient Python 3 program# to find length of# the longest prefix# which is also suffix # Returns length of the longest prefix# which is also suffix and the two do# not overlap. This function mainly is# copy computeLPSArray() of in below post# https://www.geeksforgeeks.org/searching-for-patterns-set-2-kmp-algorithm/def longestPrefixSuffix(s) :    n = len(s)    lps = [0] * n   # lps[0] is always 0      # length of the previous    # longest prefix suffix    l = 0         # the loop calculates lps[i]    # for i = 1 to n-1    i = 1    while (i < n) :        if (s[i] == s[l]) :            l = l + 1            lps[i] = l            i = i + 1                 else :             # (pat[i] != pat[len])            # This is tricky. Consider            # the example. AAACAAAA            # and i = 7. The idea is            # similar to search step.            if (l != 0) :                l = lps[l-1]                  # Also, note that we do                # not increment i here                         else :                 # if (len == 0)                lps[i] = 0                i = i + 1      res = lps[n-1]      # Since we are looking for    # non overlapping parts.    if(res > n/2) :        return n//2    else :        return res           # Driver program to test above functions = "abcab"print(longestPrefixSuffix(s))  # This code is contributed# by Nikita Tiwari.
// Efficient C# program to find length of// the longest prefix which is also suffixusing System; class GFG {         // Returns length of the longest prefix    // which is also suffix and the two do    // not overlap. This function mainly is    // copy computeLPSArray() of in below post    // https://www.geeksforgeeks.org/searching-    // for-patterns-set-2-kmp-algorithm/    static int longestPrefixSuffix(string s)    {        int n = s.Length;             int []lps = new int[n];                 // lps[0] is always 0        lps[0] = 0;             // length of the previous        // longest prefix suffix        int len = 0;             // the loop calculates lps[i]        // for i = 1 to n-1        int i = 1;        while (i < n)        {            if (s[i] == s[len])            {                len++;                lps[i] = len;                i++;            }                         // (pat[i] != pat[len])            else            {                                 // This is tricky. Consider                // the example. AAACAAAA                // and i = 7. The idea is                // similar to search step.                if (len != 0)                {                    len = lps[len-1];                         // Also, note that we do                    // not increment i here                }                                 // if (len == 0)                else                {                    lps[i] = 0;                    i++;                }            }        }             int res = lps[n-1];             // Since we are looking for        // non overlapping parts.        return (res > n/2) ? n/2 : res;    }         // Driver program    public static void Main ()    {        string s = "abcab";                 Console.WriteLine(longestPrefixSuffix(s));    }} // This code is contributed by vt_m.
<?php// Efficient PHP program to find length of// the longest prefix which is also suffix // Returns length of the longest prefix// which is also suffix and the two do// not overlap. This function mainly is// copy computeLPSArray() of in below post// https://www.geeksforgeeks.org/searching-for-patterns-set-2-kmp-algorithm/function longestPrefixSuffix($s){    $n = strlen($s);     $lps[$n] = NULL;         // lps[0] is always 0    $lps[0] = 0;     // length of the previous    // longest prefix suffix    $len = 0;     // the loop calculates lps[i]    // for i = 1 to n-1    $i = 1;    while ($i < $n)    {        if ($s[$i] == $s[$len])        {            $len++;            $lps[$i] = $len;            $i++;        }                 // (pat[i] != pat[len])        else        {                         // This is tricky. Consider            // the example. AAACAAAA            // and i = 7. The idea is            // similar to search step.            if ($len != 0)            {                $len = $lps[$len-1];                 // Also, note that we do                // not increment i here            }                         // if (len == 0)            else            {                $lps[$i] = 0;                $i++;            }        }    }     $res = $lps[$n-1];     // Since we are looking for    // non overlapping parts.    return ($res > $n/2)? $n/2 : $res;}     // Driver Code    $s = "abcab";    echo longestPrefixSuffix($s); // This code is contributed by nitin mittal?>
<script> // Efficient javascript program to find length of// the longest prefix which is also suffix{// Returns length of the longest prefix// which is also suffix and the two do// not overlap. This function mainly is// copy computeLPSArray() of in below post// https://www.geeksforgeeks.org/searching-// for-patterns-set-2-kmp-algorithm/function longestPrefixSuffix(s){    var n = s.length;     var lps = Array.from({length: n}, (_, i) => 0);         // lps[0] is always 0    lps[0] = 0;     // length of the previous    // longest prefix suffix    var len = 0;     // the loop calculates lps[i]    // for i = 1 to n-1    var i = 1;    while (i < n)    {        if (s.charAt(i) == s.charAt(len))        {            len++;            lps[i] = len;            i++;        }                  // (pat[i] != pat[len])        else        {            // This is tricky. Consider            // the example. AAACAAAA            // and i = 7. The idea is            // similar to search step.            if (len != 0)            {                len = lps[len-1];                 // Also, note that we do                // not increment i here            }                         // if (len == 0)            else            {                lps[i] = 0;                i++;            }        }    }     var res = lps[n-1];     // Since we are looking for    // non overlapping parts.    return (res > n/2)? n/2 : res;} // Driver programvar s = "abcab";document.write(longestPrefixSuffix(s));  // This code is contributed by 29AjayKumar  </script>
2
 
Please refer computeLPSArray() of KMP search for explanation.Time Complexity : O(n) Auxiliary Space : O(n) 
Solution using RegEx: 
Python3
# Python code to find length of the longest# prefix which is also suffiximport re s = "ABCABCABCABCABC" # Example input print(len(re.findall(r'^(\w*).*\1$',s)[0]))
6
 
nitin mittal
SouravBiswas3
acuminous
anurag852001
Govardhini_sarvaigari
shikhasingrajput
29AjayKumar
sumithanjage152
Pattern Searching
Searching
Strings
Searching
Strings
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check if an URL is valid or not using Regular Expression
How to check if string contains only digits in Java
Check if a string contains uppercase, lowercase, special characters and numeric values
Applications of String Matching Algorithms
Suffix Array | Set 1 (Introduction)
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
Search an element in a sorted and rotated array
Find the Missing Number