×

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

B+ Tree in Data Structure

A B-Tree extension called B+ Tree, which enables effective search, insertion, and deletion operations. Both Records and keys can be stored in internal and leaf nodes in a B tree. Contrarily,...

4 minutes read.

Deletion Operation from A B Tree

This article will show the deletion operation through the b tree in C++ programming language. Implementation #include <iostream> using namespace std; class B_TreeNod {   int *kys;   int m;   BTreeNod **C;   int j;   bool leaf;  ...

5 minutes read.

Red Black Tree vs AVL Tree: Data Structure

Difference Between Red Black Tree vs AVL Tree Red Black Tree: A red-black tree is referred as self-balancing binary search tree. In red-black, each node stores an extra bit that determines...

4 minutes read.

Reverse a Linked List in groups of given size

Reverse a Linked List in groups of given size This article will explain how to reverse a linked list in groups of given size. Here we have given a linked list...

2 minutes read.

What Should We Learn First? Trees or Graphs in Data Structures

A data structure is a database used to store and manage data and optimize and manage computing resources. A data structure is a form used intelligently and quickly to store,...

6 minutes read.

Sorting Algorithms in Data Structures

A sorting algorithm is used to organize the elements of an array or list. Sorting an array, for example. Unsorted array 572941 Sorted array 124579 We're sorting the array in ascending order right now. This procedure...

4 minutes read.

Count pairs from two linked lists whose sum is equal to a given value

Count pairs from two linked lists whose sum is equal to a given value In this problem, we have given two linked lists of size n1 and n2 with distinct elements...

4 minutes read.

Right side view of binary tree

The right view of the binary tree is generally known to be that side viewed from the right direction of the point of view. To be more precise, the right-side...

8 minutes read.

Buffer overflow attack with examples

You have undoubtedly faced the term buffer overflow in your programming journey. Many times it occurs when we try to run a piece of code with user input, but it...

4 minutes read.

Insertion Sort vs Bubble Sort

In this article, we will see the major differences between Insertion Sort and Bubble Sort. Before that, let’s have a quick overview of what these sorting algorithms are and what’s...

4 minutes read.

Permutation Sort or Bogo Sort

In Permutation Sort or Bogo Sort, you have been given one array, which consists of different values. You have to sort the array using BOGO sort. Let’s take an example: Input-...

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

Function to Insert a Node in a Binary Search Tree

Implementation // writing C++ code that will help us in implementing the insertion operation in a binary search tree. #include <bits/stdc++.h> using namespace std; // creating a new binary search tree node struct __nod { int...

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

What are Forest Trees in Data Structure

Data structure A data model manages and optimizes computer resources, and a database stores and manages data. It's one of many uses for data structures to hold data. Data structures come...

5 minutes read.

Binary Search Tree

Binary Search Tree: A binary search tree is a type of tree in which every node is organized in the sorted order. It is also called an ordered binary tree. Properties...

4 minutes read.

Bubble Sort vs Quick Sort

In this article, we are going to compare two sorting techniques, Bubble sort and Quick Sort. In starting, we will first discuss the idea of sorting an array using bubble...

7 minutes read.

Serialize and Deserialize Binary Trees

In order to save a tree in a file that can later be restored, serialisation is used. The tree's structure must be preserved. Deserialization involves reading a tree from a...

4 minutes read.

Remove duplicates from an unsorted Linked List

Remove duplicates from an unsorted Linked List This article will explain how we can remove duplicates from unsorted linked lists. Here we have given an unsorted singly linked list and will...

3 minutes read.

Optimal binary search tree in DSA

Implementation // A simple way of the recursive implementation of the optimal search that we will perform on the binary tree.   #include <bits/stdc++.h> using namespace std; // we have to create a basic utility...

8 minutes read.