The Wayback Machine - https://web.archive.org/web/20240906185205/https://www.geeksforgeeks.org/longest-prefix-also-suffix/
Open In App

Longest prefix which is also suffix

Last Updated : 29 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Show Topics
Solve Problem
Hard
27.91%
1.1L

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 : S = aabcdaabc
Output : 4
Explanation: The string “aabc” is the longest prefix which is also suffix.

Input : S = abcab
Output : 2

Input : S = aaaa
Output : 2

Recommended Practice

Naive approach:

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++




// 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 suffix
int largest_prefix_suffix(const std::string& str)
{
    int n = str.length();
  
    // If the length of the string is less than 2, there
    // can't be a non-overlapping prefix and suffix, so
    // return 0.
    if (n < 2) {
        return 0;
    }
  
    // Initialize the length of the longest prefix which is
    // also a suffix.
    int len = 0;
    int i = 0;
  
    // Iterate through the first half of the string.
    while (i < n / 2) {
        int j1 = 0, j2 = (n - 1) - i;
        int isPrefixSuffix = 1;
  
        // Check if characters at corresponding positions in
        // the first half (j1) and the second half (j2) of
        // the string are equal.
        while (j1 <= i) {
  
            // If any pair of characters doesn't match, it's
            // not a prefix-suffix.
            if (str[j1] != str[j2]) {
                isPrefixSuffix = 0;
            }
            j1++;
            j2++;
        }
  
        // If it's a prefix-suffix, update the length.
        if (isPrefixSuffix == 1)
            len = i + 1;
        i++;
    }
  
    // Return the length of the longest prefix which is also
    // a suffix.
    return len;
}
  
// Driver code
int main()
{
    string s = "blablabla";
  
    // Function Call to find the length of the longest
    // prefix which is also a suffix
    cout << largest_prefix_suffix(s);
  
    return 0;
}


Java




public class LongestPrefixSuffix {
    // Function to find the length of the longest prefix
    // which is also a suffix
    public static int largestPrefixSuffix(String str)
    {
        int n = str.length();
  
        // If the length of the string is less than 2, there
        // can't be a non-overlapping prefix and suffix, so
        // return 0.
        if (n < 2) {
            return 0;
        }
  
        // Initialize the length of the longest
        // prefix which is also a suffix.
        int len = 0;
        
        int i = 0;
  
        // Iterate through the first half of the string.
        while (i < n / 2) {
            int j1 = 0, j2 = (n - 1) - i;
            boolean isPrefixSuffix = true;
  
            // Check if characters at corresponding
            // positions in the first half (j1) and the
            // second half (j2) of the string are equal.
            while (j1 <= i) {
  
                // If any pair of characters doesn't match,
                // it's not a prefix-suffix.
                if (str.charAt(j1) != str.charAt(j2)) {
                    isPrefixSuffix = false;
                }
                j1++;
                j2++;
            }
            // If it's a prefix-suffix, update the length.
            if (isPrefixSuffix)
                len = i + 1;
            i++;
        }
  
        // Return the length of the longest prefix which is
        // also a suffix.
        return len;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String s = "blablabla";
  
        // Function Call to find the length of the longest
        // prefix which is also a suffix
        System.out.println(largestPrefixSuffix(s));
    }
}


Python3




# Function to find the length of the longest prefix which is also a suffix
def largest_prefix_suffix(s):
    n = len(s)
  
    # If the length of the string is less than 2, there can't be a non-overlapping
    # prefix and suffix, so return 0.
    if n < 2:
        return 0
    lenn = 0  # Initialize the length of the longest prefix which is also a suffix.
    i = 0
  
    # Iterate through the first half of the string.
    while i < n // 2:
        j1 = 0
        j2 = (n - 1) - i
        is_prefix_suffix = True
  
        # Check if characters at corresponding positions in the first half (j1)
        # and the second half (j2) of the string are equal.
        while j1 <= i:
            if s[j1] != s[j2]:
                is_prefix_suffix = False  # If any pair of characters doesn't match, it's not a prefix-suffix.
            j1 += 1
            j2 += 1
        if is_prefix_suffix:
            lenn = i + 1  # If it's a prefix-suffix, update the length.
        i += 1
  
    # Return the length of the longest prefix which is also a suffix.
    return lenn
  
# Driver code
s = "blablabla"
# Function Call to find the length of the longest prefix which is also a suffix
print(largest_prefix_suffix(s))


C#




using System;
  
class Program {
    // Function to find the length of the longest prefix
    // which is also a suffix
    static int LargestPrefixSuffix(string str)
    {
        int n = str.Length;
  
        // If the length of the string is less than 2, there
        // can't be a non-overlapping prefix and suffix, so
        // return 0.
        if (n < 2) {
            return 0;
        }
        int len = 0; // Initialize the length of the longest
                     // prefix which is also a suffix.
        int i = 0;
  
        // Iterate through the first half of the string.
        while (i < n / 2) {
            int j1 = 0;
            int j2 = (n - 1) - i;
            bool isPrefixSuffix = true;
  
            // Check if characters at corresponding
            // positions in the first half (j1) and the
            // second half (j2) of the string are equal.
            while (j1 <= i) {
                if (str[j1] != str[j2]) {
                    isPrefixSuffix
                        = false; // If any pair of
                                 // characters doesn't
                                 // match, it's not a
                                 // prefix-suffix.
                }
                j1++;
                j2++;
            }
            if (isPrefixSuffix)
                len = i + 1; // If it's a prefix-suffix,
                             // update the length.
            i++;
        }
  
        // Return the length of the longest prefix which is
        // also a suffix.
        return len;
    }
  
    // Driver code
    static void Main()
    {
        string s = "blablabla";
  
        // Function Call to find the length of the longest
        // prefix which is also a suffix
        Console.WriteLine(LargestPrefixSuffix(s));
    }
}


Javascript




// Function to find the length of the longest prefix which is also a suffix
function largestPrefixSuffix(str) {
    const n = str.length;
  
    // If the length of the string is less than 2, there can't be a non-overlapping
    // prefix and suffix, so return 0.
    if (n < 2) {
        return 0;
    }
    let len = 0; // Initialize the length of the longest prefix which is also a suffix.
    let i = 0;
  
    // Iterate through the first half of the string.
    while (i < Math.floor(n / 2)) {
        let j1 = 0;
        let j2 = (n - 1) - i;
        let isPrefixSuffix = true;
  
        // Check if characters at corresponding positions in the first half (j1)
        // and the second half (j2) of the string are equal.
        while (j1 <= i) {
            if (str.charAt(j1) !== str.charAt(j2)) {
                isPrefixSuffix = false; // If any pair of characters doesn't match, it's not a prefix-suffix.
            }
            j1++;
            j2++;
        }
        if (isPrefixSuffix) {
            len = i + 1; // If it's a prefix-suffix, update the length.
        }
        i++;
    }
  
    // Return the length of the longest prefix which is also a suffix.
    return len;
}
  
// Driver code
const s = "blablabla";
  
// Function Call to find the length of the longest prefix which is also a suffix
console.log(largestPrefixSuffix(s));


Output

3


Time Complexity: O(n^2)
Auxiliary Space: O(1)

Longest prefix which is also suffix using KMP algorithm:

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].

Below is the implementation:

C++




// 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
int longestPrefixSuffix(string str)
{
          vector<int> A(str.size(), 0);
        int j = 0, i = 1;
          
        // Loop to calculate the prefix array
        while(i < str.size())
        {
            if(str[i] == str[j])
            {
                // Increment j by 1 and assign the value to the prefix array
                A[i] = j+1;
                j++;
                i++;
            }
            else
            {
                if(j==0)
                    i++;
                else
                    // Set j to the previous value in the prefix array
                    j = A[j-1];
                  
            }
        }
  
        // Return the last element of the prefix array
        return A.back();
}
  
// Driver program to test above function
int main()
{
    string s = "abadabab";
    cout << longestPrefixSuffix(s);
    return 0;
}
  
// Corrected by Nilanshu Yadav


Java




// 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
    // for-patterns-set-2-kmp-algorithm/
    static int longestPrefixSuffix(String str)
    {
      int[] A = new int[str.length()];
        int j = 0, i = 1;
        while(i < str.length())
        {
            if(str.charAt(i) == str.charAt(j))
            {
                A[i] = j+1;
                j++;
                i++;
            }
            else
            {
                if(j==0)
                    i++;
                else
                    j = A[j-1];
                  
            }
        }
  
        return A[str.length()-1];
    }
      
    // Driver program 
    public static void main (String[] args) 
    {
        String s = "bbabbabb";
        System.out.println(longestPrefixSuffix(s));
    }
}
  
// This code is contributed by Anant Agarwal.
// Corrected by Nilanshu Yadav


Python3




# 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
  
  
def longestPrefixSuffix(str):
    # initialize an array of size equal to the length of the string
    A = [0 for i in range(len(str))]
  
    j = 0  # initialize j to 0
    i = 1  # initialize i to 1
  
    while i < len(str):  # loop through the string
  
        if str[i] == str[j]:  # if the characters at i and j are equal
  
            A[i] = j+1  # update the lps array at index i with (j+1)
  
            j += 1  # increment j by 1
            i += 1  # increment i by 1
  
        else:  # if the characters at i and j are not equal
  
            if j == 0:  # if j is already at the first position
  
                i += 1  # increment i by 1
  
            else:  # if j is not at the first position
  
                # update j with the value at the previous index in the lps array
                j = A[j-1]
  
    return A[-1]  # return the last element of the lps array.
  
  
# Driver program to test above function
s = "bbabbabb"
print(longestPrefixSuffix(s))
  
  
# This code is contributed
# by Nikita Tiwari.
# Corrected by Nilanshu Yadav


C#




// Efficient C# program to find length of 
// the longest prefix which is also suffix
using 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
    // 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.


Javascript




<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
// for-patterns-set-2-kmp-algorithm/
function longestPrefixSuffix(str)
{
         let A = new Array(s.length).fill(0);
        let j = 0, i = 1;
          
        while(i < s.length)
        {
            if(s[i] == s[j])
            {
                A[i] = j+1;
                j++;
                i++;
            }
            else
            {
                if(j==0)
                    i++;
                else
                    j = A[j-1];
                  
            }
        }
  
        return A[A.length - 1];
}
  
// Driver program 
var s = "abcab";
document.write(longestPrefixSuffix(s));
  
  
// This code is contributed by 29AjayKumar 
  
  
</script>


PHP




<?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
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
?>


Output

2


Time Complexity: O(n) 
Auxiliary Space: O(n)

Please refer computeLPSArray() of KMP search for an explanation.
 



Previous Article
Next Article

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: str = "aaaa" Output: aa Approach: The idea is to
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 = "aaaa" "aa" is a prefix, suffix and present insid
10 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 of this article is attached here.Approach: The impl
9 min read
Maximum prefix sum which is equal to suffix sum such that prefix and suffix do not overlap
Given an array arr[] of N Positive integers, the task is to find the largest prefix sum which is also the suffix sum and prefix and suffix do not overlap. Examples: Input: N = 5, arr = [1, 3, 2, 1, 4]Output: 4Explanation: consider prefix [1, 3] and suffix [4] which gives maximum prefix sum which is also suffix sum such that prefix and suffix do not
7 min read
Check if count of substrings in S with string S1 as prefix and S2 as suffix is equal to that with S2 as prefix and S1 as suffix
Given three strings S, S1, and S2, the task is to check if the number of substrings that start and end with S1 and S2 is equal to the number of substrings that start and end with S2 and S1 or not. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: S = "helloworldworldhelloworld", S1 = "hello", S2 = "world"Output: NoExpla
8 min read
Longest palindromic string formed by concatenation of prefix and suffix of a string
Given string str, the task is to find the longest palindromic substring formed by the concatenation of the prefix and suffix of the given string str. Examples: Input: str = "rombobinnimor" Output: rominnimor Explanation: The concatenation of string "rombob"(prefix) and "mor"(suffix) is "rombobmor" which is a palindromic string. The concatenation of
11 min read
Longest Palindrome in a String formed by concatenating its prefix and suffix
Given a string str consisting of lowercase English letters, the task is to find the longest palindromic string T which satisfies the following condition: T = p + m + s where p and s are the prefix and the suffix of the given string str respectively and the string m is either the prefix or suffix of the string str after removing both p and s from it
13 min read
Longest substring whose any non-empty substring not prefix or suffix of given String
Given a string S of length N, the task is to find the length of the longest substring X of the string S such that: No non-empty substring of X is a prefix of S.No non-empty substring of X is a suffix of S.If no such string is possible, print −1. Examples: Input: S = "abcdefb"Output: 4Explanation: cdef is the substring satisfying the conditions. Inp
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 Input: s = "abcdabc"Output: -1 Approach: The idea
7 min read
Count of indices up to which prefix and suffix sum is equal for given Array
Given an array arr[] of integers, the task is to find the number of indices up to which prefix sum and suffix sum are equal. Example: Input: arr = [9, 0, 0, -1, 11, -1]Output: 2Explanation: The indices up to which prefix and suffix sum are equal are given below:At index 1 prefix and suffix sum are 9At index 2 prefix and suffix sum are 9 Input: arr
15+ min read
Count of indices for which the prefix and suffix product are equal
Given an array arr[] of integers, the task is to find the number of indices for which the prefix product and the suffix product are equal. Example: Input: arr = [4, -5, 1, 1, -2, 5, -2]Output: 2Explanation: The indices on which the prefix and the suffix product are equal are given below:At index 2 prefix and suffix product are 20At index 3 prefix a
14 min read
Construct array B as last element left of every suffix array obtained by performing given operations on every suffix of given array
Given an array arr[] of N integers, the task is to print the last element left of every suffix array obtained by performing the following operation on every suffix of the array, arr[]: Copy the elements of the suffix array into an array suff[].Update ith suffix element as suff[i] = (suff[i] OR suff[i+1]) - (suff[i] XOR suff[i+1]) reducing the size
9 min read
Find the suffix factorials of a suffix sum array of the given array
Given an array arr[] consisting of N positive integers, the task is to find the suffix factorials of a suffix sum array of the given array. Examples: Input: arr[] = {1, 2, 3, 4}Output: {3628800, 362880, 5040, 24}Explanation: The suffix sum of the given array is {10, 9, 7, 4}. Therefore, suffix factorials of the obtained suffix sum array is {10!, 9!
5 min read
Suffix Tree Application 4 - Build Linear Time Suffix Array
Given a string, build it's Suffix Array We have already discussed following two ways of building suffix array: Naive O(n2Logn) algorithmEnhanced O(nLogn) algorithm Please go through these to have the basic understanding. Here we will see how to build suffix array in linear time using suffix tree.As a prerequisite, we must know how to build a suffix
15+ min read
Difference between Suffix Array and Suffix Tree
Suffix Array and Suffix Tree are data structures used for the efficient string processing and pattern matching. They provide the different ways to the store and query substrings each with the unique characteristics and use cases. Understanding the differences between them helps in the choosing the right data structure for the specific applications.
3 min read
Longest string in an array which matches with prefix of the given string
Given an array of strings arr[] and Q queries where each query consists of a string str, the task is to find the longest string in the array that matches with prefix of the given string str i.e. the string must be prefix of str. Examples: Input: arr[] = {"GeeksForGeeks", "GeeksForGeeksd", "Arnab", "Art"}, q[] = {"GeeksForGeeks", "Ar", "Art"} Output
8 min read
Longest string which is prefix string of at least two strings
Given a set of strings of the same length, we need to find the length of the longest string, which is a prefix string of at least two strings. Examples: Input: ["abcde", "abcsd", "bcsdf", "abcda", "abced"] Output: 4 Explanation: Longest prefix string is "abcd". Input: ["pqrstq", "pwxyza", "abcdef", "pqrstu"] Output: 5 Approach: Starting from the 0t
6 min read
Length of longest prefix anagram which are common in given two strings
Given two strings str1 and str2 of the lengths of N and M respectively, the task is to find the length of the longest anagram string that is prefix substring of both strings. Examples: Input: str1 = "abaabcdezzwer", str2 = "caaabbttyh"Output: 6Explanation: Prefixes of length 1 of string str1 and str2 are "a", and "c".Prefixes of length 2 of string
8 min read
Remove longest prefix of the String which has duplicate substring
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 rema
5 min read
Maximum array sum with prefix and suffix multiplications with -1 allowed
Given N elements (both positive and negative). Find the maximum sum, provided that the first operation is to take some prefix of the sequence and multiply all numbers in this prefix by -1. The second operation is to take some suffix and multiply all numbers in it by -1. The chosen prefix and suffix may intersect. What is the maximum total sum of th
8 min read
String from prefix and suffix of given two strings
Given two strings a and b, form a new string of length l, from these strings by combining the prefix of string a and suffix of string b. Examples : Input : string a = remuneration string b = acquiesce length of pre/suffix(l) = 5 Output :remuniesce Input : adulation obstreperous 6 Output :adulatperous Approach : Get first l letters from string a, an
4 min read
Counting common prefix/suffix strings in two lists
Given two Lists of strings s1 and s2, you have to count the number of strings in s2 which is either a suffix or prefix of at least one string of s1. Examples: Input: s1 = ["cat", "catanddog", "lion"], s2 = ["cat", "dog", "rat"]Output: 2Explanation: String "cat" of s2 is a prefix of "catanddog"string "dog" of s2 is suffix of "catanddog" Input: s1 =
4 min read
Check if suffix and prefix of a string are palindromes
Given a string 's', the task is to check whether the string has both prefix and suffix substrings of length greater than 1 which are palindromes. Print 'YES' if the above condition is satisfied or 'NO' otherwise. Examples: Input : s = abartbb Output : YES Explanation : The string has prefix substring 'aba' and suffix substring 'bb' which are both p
8 min read
Index with Minimum sum of prefix and suffix sums in an Array
Given an array of integers. The task is to find the index [Tex]i [/Tex]in the array at which the value of prefixSum(i) + suffixSum(i) is minimum.Note: PrefixSum(i) = The sum of first i numbers of the array.SuffixSum(i) = the sum of last N - i + 1 numbers of the array.1-based indexing is considered for the array. That is an index of the first elemen
10 min read
Find index i such that prefix of S1 and suffix of S2 till i form a palindrome when concatenated
Given two strings A and B of equal lengths, the task is to find an index i such that A[0...i] and B[i+1...n-1] give a palindrome when concatenated together. If it is not possible to find such an index then print -1. Examples: Input: S1 = "abcdf", S2 = "sfgba" Output: 1 S1[0..1] = "ab", S2[2..n-1] = "gba" S1 + S2 = "abgba" which is a palindrome. Inp
12 min read
Maximize the sum of array after multiplying a prefix and suffix by -1
Given an array arr[] of length N, the task is to maximize the sum of all the elements of the array by performing the following operations at most once. Choose a prefix of the array and multiply all the elements by -1.Choose a suffix of the array and multiply all the elements by -1. Examples: Input: arr[] = {-1, -2, -3} Output: 6 Explanation: Operat
7 min read
Count indices where the maximum in the prefix array is less than that in the suffix array
Given an array arr[] of size N, the task is to find the number of prefix arrays whose maximum is less than the maximum element in the remaining suffix array. Examples: Input: arr[] = {2, 3, 4, 8, 1, 4}Output: 3Explanation:Prefix array = {2}, {2, 3}, {2, 3, 4}, {2, 3, 4, 8}, {2, 3, 4, 8, 1} Respective Suffix = {3, 4, 8, 1, 4}, {4, 8, 1, 4}, {8, 1, 4
8 min read
Count pairs of indices having equal prefix and suffix sums
Given an array arr[] of length N, the task is to find the count of pairs of indices (i, j) (0-based indexing) such that prefix sum of the subarray {arr[0], ... arr[i]} is equal to the suffix sum of the subarray {arr[N - 1], ..., arr[j]} ( 0 ? i, j &lt; N). Examples: Input: arr[] = {1, 2, 1, 1}Output: 3Explanation: The 3 possible pairs of indices ar
6 min read
Search a string in the dictionary with a given prefix and suffix for Q queries
Given an array arr[] consisting of N strings and Q queries in form of two strings prefix and suffix, the task for each query is to find any one string in the given array with the given prefix and suffix. If there exists no such string then print "-1". Examples: Input: arr[] = {"apple", "app", "biscuit", "mouse", "orange", "bat", "microphone", "mine
15+ min read
Find position i to split Array such that prefix sum till i-1, i and suffix sum till i+1 are in GP with common ratio K
Given an array, arr[] and a positive integer K. The task is to find the position say i of the element in arr[] such that prefix sum till i-1, i and suffix sum till i+1 are in Geometric Progression with common ratio K. Examples: Input: arr[] = { 5, 1, 4, 20, 6, 15, 9, 10 }, K = 2Output: 4Explanation: The following operations are performed to get req
8 min read