×

Length of longest palindrome in a linked list using O(1) extra space

Length of longest palindrome in a linked list using O(1) extra space

In this problem, we need to find the length of the longest palindrome list that is present in given linked list.

Examples:

Input: List = 2 ->4 ->7 ->4 ->2 ->12 ->0

Output: 5

The longest palindrome list is 2 ->4 ->7 ->4 ->2

Input:List = 12 ->5 ->5 ->3 ->11

Output:2

The longest palindrome list is 5 -> 5

Method:

There is a simple solution available for this problem, we can copy the linked list to the array and try to find the longest palindromic subarray in the array, but this solution is not allowed here because this solution requires extra space. So we will see another method for the given problem.

Another concept is based on the iterative linked list reverse process. We will traverse the given linked list and reverse one by one every prefix of the linked list from the left side. After this, we will find the longest common list beginning from the reversed prefix and the list after the reversed prefix.

Java program to find longest palindrome sublist in a list in O(1) time.

 importjava.util.*;
 class Node
 {
             int data;
             Node next;
             Node(int d)
             {
                         data = d;
                         next = null;
             }
 }
 public class LongestPalindrome
 {
 Node head,tail;
 // For adding a node the end of the linked list
 public void addToTheLast(Node node)
 {
 if (head == null) {
 head = node;
 tail = head;
   }
 else {  
 tail.next=node;
 tail = tail.next;
   }
 }
 /* Function to print linked list */
 void traverse(Node head)
     {
         Node temp = head;
 while (temp != null)
         {
 System.out.print(temp.data+" ");
 temp = temp.next;
         } 
 System.out.println();
     }
 // function for counting the common elements
 static int countCommon(Node a, Node b)
 {
 int count = 0;
 for (; a != null && b != null;
             a = a.next, b = b.next)
 if (a.data == b.data)
             ++count;
 else
 break;
 return count;
 }
 //For finding the longest palindrome sublist in the linked list
 static int maxPalindrome(Node head)
 {
 int result = 0;
     Node prev = null, curr = head;
     // loop till the end of the linked list
 while (curr != null)
     {
         Node next = curr.next;
 curr.next = prev;
 result = Math.max(result,
                     2 * countCommon(prev, next)+1);
 result = Math.max(result,
                     2 * countCommon(curr, next));
 prev = curr;
 curr = next;
     }
 return result;
 }
 // Driver Function    
 public static void main(String args[])
             {
                                     LongestPalindromeob = new LongestPalindrome();
                                     ob.addToTheLast(new Node(2));
                                     ob.addToTheLast(new Node(4));
                                     ob.addToTheLast(new Node(3));
                                     ob.addToTheLast(new Node(3));
                                     ob.addToTheLast(new Node(4));
                                     ob.addToTheLast(new Node(22));
                                     ob.traverse(ob.head);
                                     System.out.print("Length of the longest palindrom list is:-");
 int res = ob.maxPalindrome(ob.head);
                                     System.out.print(res);
             }
 } 

Output:

Length of longest palindrome

Time Complexity:The time complexity of the above method is O(n^2).

Space Complexity:The time complexity of the above method isO(1), which is constant space.


Related Topics

Convert Binary Tree into a Threaded Binary Tree

Implementation /*Writing a C++ program that will help us change the binary tree into a threaded binary tree and help us transform. */ #include <bits/stdc++.h> using namespace std; /*Creating the structure of a node...

11 minutes read.

AVL Tree

AVL Tree AVL Tree is referred to as self-balanced or height-balanced binary search tree where the difference between heights of its left subtree and right subtree (Balance Factor) can't more than...

25 minutes read.

Deletion Operation of the binary search tree in C++ language

A typical binary search tree implements some order to carry out the arrangements. As the name suggests, each parent node should have at most two children. The main rule in...

4 minutes read.

Horizontal and Vertical Scaling

Being a software engineer, you would have designed a website or application and deployed it on any server. Imagine that the developed application starts getting popular, and many users engage...

6 minutes read.

Intersection Point in Y Shaped Linked Lists in Java

Intersection Point in Y Shaped Linked Lists in Java In this article, we are going to see how to find the intersection point in a Y-shaped linked list. Method 1: We need to...

4 minutes read.

Doubly Linked List

Doubly Linked List Doubly linked list is another kind of Linked list. Doubly linked list contains two pointers for navigation. In this, we can traverse the list in both directions, either...

4 minutes read.

Binary tree insertion

As we all know, a binary tree has a maximum of two children and helps us manage the info correctly. Here the name of the tree itself portrays the mechanism...

4 minutes read.

About Data Structures

What exactly are data structures? A data structure is a type of storage that is used to organise and store data. It is a method of organising data on a computer...

5 minutes read.

Depth of binary tree

We all know that a binary tree is a kind of tree that helps us maintain the order and balance of the tree. It is a type of tree in...

4 minutes read.

Primitive Data Structure in C

The data structure is a logical or mathematical model for organizing and structuring the main memory or elements. We can classify the data structures in two ways one is primitive, and...

10 minutes read.

Circular Queue

Circular Queue Circular Queue is special type queue, which follows First in First Out (FIFO) rule and as well as instead of ending queue at the last position, it starts again...

4 minutes read.

Comb Sort

Brush sort is a fairly direct orchestrating computation at first arranged by Wlodzimierz Dobosiewicz and Artur Borowy in 1980, later rediscovered (and given the name "Combsort") by Stephen Lacey and...

5 minutes read.

Operations on 2D-Arrays

Two Dimensional Array Operations Adding Elements to Two-D Arrays We must put data in both rows and columns when inserting items in 2-D Arrays. As a result, we employ the idea of...

10 minutes read.

Winner tree in Data Structures

Tree Data structure A tree is a hierarchical and non-linear data structure with nodes. Each node in the Tree contains a message value and stores the name passed to another ("child")...

6 minutes read.

Heap Data Structure

In this article, we will learn in detail about Heap (Min heap and Max heap). Before going to the main topics, let’s have a look at what is complete binary...

19 minutes read.

Merge two sorted linked lists

Merge two sorted linked lists In this article, we are going to learn how to merge two linked lists. Here we have given two linked lists that are sorted in increasing...

7 minutes read.

Binary search tree traversal in-order pre-order post-order examples

A binary search tree is a type of non-linear tree in which the tree contains at least two nods. It is called binary because of its nature that states bi...

8 minutes read.

Create a binary search tree

Implementation In this section of the article, we will see the usage and mechanism of how we will create a given binary tree. Let's observe these in more depth and then...

7 minutes read.

Bitwise Operators and their Important Tricks

In most of the programs you write today, you deal with data types comprising bytes, such as integer, float, double, etc. Dealing with bytes? It is a quite normal task,...

5 minutes read.

B+ Tree Program in Q language

A B+ tree is just an improvised version of a self-balancing and well-maintained tree in which all the key values that hold valuable information is present at the bottom, which...

9 minutes read.