Longest Palindromic Substring

    by nikoo28

    Let us suppose that we are given a string ‘str’. You need to find out the longest palindrome as a substring. Note that the elements of the string should be contagious.

    Example 1:
    Input: "aaebabad"
    Output: "bab"
    Note: "aba" is also a valid answer

    Example 2:
    Input: "cbeereed"
    Output: "eeree"

    Terminology:

    Palindrome: A palindrome is a type of string that reads the same when reading left to right and right to left. An example of a palindrome can be “level”, “racecar”, “kayak” etc.

    Sub-string: A string formed formed using the characters of the string that may or may not contain repetitions.

    Brute Force Method:

    As soon as you see the problem, the most first thought that comes to your mind would be to find all the sub-strings from the given string and keep a track of the longest one that we find. That will eventually land you to the right answer, but the time complexity of such an algorithm would be enormous. There total number of sub-strings would be =\frac{n\ *\ (n\ -\ 1)}{2}

    This would cause the complexity to quickly reach O(n^2) and we can check if a string is a palindrome in O(n) time, resulting in a total complexity of O(n^3). This is something we do not want as it will take up a lot of time.

    Optimized Method:

    Let us try to aim for a method with a complexity of )(n^2). The algorithm will look something like:

    • Start traversing the string from the first character to the last character.
    • For each of the position ‘i’ in the string, find out the largest palindrome having an even length and an odd length. Note that a single letter can also be a palindrome.
    • The minimum valid even length would be 2. Eg: “aa”, “cc”, xx”.
    • The minimum valid odd length would be 1. Eg: “a”, “v”.
    • Hence for each of the character in the string, navigate in both left and right directions till the condition for palindrome is satisfied.
    • Keep a track of the largest palindrome encountered so far.
    • At the end of this loop, you would have the longest palindrome sub-string.
    Code:
    String longestPalindrome(String str) {
    
        if (str.length() <= 1)
          return str;
    
        String LPS = "";
    
        for (int i = 1; i < str.length(); i++) {
    
          // Consider odd length
          int low = i;
          int high = i;
          // Keep extending in both left and right directions till the
          // conditions for a palindrome are met
          while(str.charAt(low) == str.charAt(high)) {
            low--;
            high++;
    
            // Terminating condition if we reach the end/start of the string
            if (low == -1 || high == str.length())
              break;
          }
    
          // Indexes low and high can be used to extract the substring
          String palindrome = str.substring(low+1, high);
          if (palindrome.length() > LPS.length()) {
            // Capture the longest palindrome found
            LPS = palindrome;
          }
    
          // Consider even length
          low = i - 1;
          high = i;
          while(str.charAt(low) == str.charAt(high)) {
            low--;
            high++;
    
            if (low == -1 || high == str.length())
              break;
          }
    
          palindrome = str.substring(low+1, high);
          if (palindrome.length() > LPS.length()) {
            // Similarly, keep a track of the longest even length palindrome
            LPS = palindrome;
          }
        }
    
        return LPS;
      }
    Code language: Java (java)

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

    A working solution can be found here: https://ideone.com/GvH6g0
    This code can also be obtained on Github.
    A similar problem is available on Leetcode.
    A similar question: length of longest palindrome that can be built from a string.

    Video explanation:
    YouTube player

    2 comments
    0 FacebookTwitterLinkedinWhatsappEmail
  • Question: Given an array A, find the sum of maximum sum of two non-overlapping subarrays, with lengths L and M.In other words, return the largest V for which V = (A[i] + A[i+1] …. A[i+L-1]) + (A[j] + A[j+1] …. A[j+M-1])Input: A = {3, 8, 1, 3, 2, 1, 8, 9, 0}; L = 3, M = 2Output: 29 The problem statement is quite clear. We need to find 2 contiguous sub-arrays from an array Add the elements of both these arrays The sum should be the maximum possible sum…

    0 FacebookTwitterLinkedinWhatsappEmail
  • Arrays

    Array Nesting

    by nikoo28
    4 minutes read

    Question: Given a zero-indexed array ‘A’ of length ‘N’ which contains all integers from 0 to N-1. Find and return the longest length of set S, where S[i] = {A[i], A[A[i]], A[A[A[i]]], …} subjected to a particular condition. Suppose the first element in S starts with the selection of element A[i] of index = i, the next element in S should be A[A[i]], and then A[A[A[i]]],.. and so on. By that analogy, we stop adding elements as soon as we get a duplicate. Input: A = {5, 4, 0, 3,…

    0 FacebookTwitterLinkedinWhatsappEmail
  • Strings

    CamelCase matching

    by nikoo28
    3 minutes read

    Question: Given a set of queries and a pattern, we need to determine if some of those queries can be made from the given pattern by adding one or more lower case character. Output a boolean array where array[i] says true, if the query is possible, else false. Input: queries= {“StudyAlgorithms”, “StudyAlgorithmsTest”, “StanAlluring”, “SimulationAlteration”, “StopStayAlive”}pattern = “StAl” Output: {true, false, true, true, false} Let us try to understand the output.The pattern defined to us is St*Al* (if we see it in terms of a regex) StudyAlgorithms can be made as…

    0 FacebookTwitterLinkedinWhatsappEmail
  • Arrays

    Container with maximum water

    by nikoo28
    4 minutes read

    Question: Let us suppose we have a two dimensional plane where the the length of lines determine the height of a container. We need to determine the maximum capacity of water this kind of an arrangement can hold. The heights are represented by an array. Input: [1, 8, 6, 2, 5, 4, 8, 3, 7] Output: 49 Let us try to visualize the problem at hand diagrammatically. Let the array be represented as: If we try to pour water from the top in the entire arrangement you can visualize that…

    0 FacebookTwitterLinkedinWhatsappEmail
  • Question: Given an array, there is a largest element N. Check if that number is at least twice than all the other elements in the array. Return the index if it is, else return -1Input: {3, 6, 1, 0}Output: -1 6 is the largest integer, and for every other number in the array x,6 is more than twice as big as x. The index of value 6 is 1, so we return 1. Let us try to make one more exampleInput: nums = [1, 2, 3, 4] Output: -1Explanation: 4…

    0 FacebookTwitterLinkedinWhatsappEmail
  • Question: Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.Input: “abccccdd”Output: 7 In the above example, the longest palindrome in the given string is “dccaccd” whose length is 7. A palindrome consists of letters with equal partners, plus possibly a unique center (without a partner). The letter i from the left has its partner i from the right. For example in ‘abcba’, ‘aa’ and ‘bb’ are partners, and ‘c’ is a unique center. Imagine we…

    0 FacebookTwitterLinkedinWhatsappEmail

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More