Find palindromic Subarrays in a Linked List
Last Updated :
14 Sep, 2023
Given a singly Linked list, find all palindromic subarrays of length greater than two.
Examples:
Input: Linked List = 1 -> 2 -> 3 -> 2 -> 1
Output: [2, 3, 2], [1, 2, 3, 2, 1]
Input: Linked List = 1 -> 2 -> 3 -> 4 -> 3 -> 2 -> 1
Output: [3, 4, 3], [2, 3, 4, 3, 2], [1, 2, 3, 4, 3, 2, 1]
Approach: This can be solved with the following idea:
Start Iterating from the 2nd index, and check for palindrome up to that particular index. If it is a palindrome add it to the result vector.
Below are the steps involved in the implementation of the code:
- Create an arr vector and store the number in the linked list in vector.
- From k = 2 to k <= n and inside this start another loop i from 0 and n – k.
- See for palindrome in each segment and keep on adding numbers in the vector subarray.
- From the subarray add it to the 2D vector result.
- Print all the vectors in 2D vector result.
Implementation of the above approach:
C++
#include <iostream>
#include <vector>
using namespace std;
class Node {
public :
int val;
Node* next;
Node( int v)
{
val = v;
next = NULL;
}
};
vector<vector< int > > palindromicSubarrays(Node* head)
{
vector<vector< int > > result;
vector< int > arr;
Node* curr = head;
while (curr) {
arr.push_back(curr->val);
curr = curr->next;
}
int n = arr.size();
for ( int k = 2; k <= n; k++) {
for ( int i = 0; i <= n - k; i++) {
vector< int > subarray;
for ( int j = i; j < i + k; j++) {
subarray.push_back(arr[j]);
}
bool is_palindrome = true ;
int m = subarray.size();
for ( int j = 0; j < m / 2; j++) {
if (subarray[j] != subarray[m - j - 1]) {
is_palindrome = false ;
break ;
}
}
if (is_palindrome) {
result.push_back(subarray);
}
}
}
return result;
}
int main()
{
Node* head = new Node(1);
head->next = new Node(2);
head->next->next = new Node(3);
head->next->next->next = new Node(4);
head->next->next->next->next = new Node(3);
head->next->next->next->next->next = new Node(2);
head->next->next->next->next->next->next = new Node(1);
vector<vector< int > > result
= palindromicSubarrays(head);
for ( auto subarray : result) {
for ( auto num : subarray) {
cout << num << " " ;
}
cout << endl;
}
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.List;
class Node {
public int val;
public Node next;
public Node( int v)
{
val = v;
next = null ;
}
}
public class PalindromicSubarrays {
public static List<List<Integer> >
palindromicSubarrays(Node head)
{
List<List<Integer> > result = new ArrayList<>();
List<Integer> arr = new ArrayList<>();
Node curr = head;
while (curr != null ) {
arr.add(curr.val);
curr = curr.next;
}
int n = arr.size();
for ( int k = 2 ; k <= n; k++) {
for ( int i = 0 ; i <= n - k; i++) {
List<Integer> subarray = new ArrayList<>();
for ( int j = i; j < i + k; j++) {
subarray.add(arr.get(j));
}
boolean is_palindrome = true ;
int m = subarray.size();
for ( int j = 0 ; j < m / 2 ; j++) {
if (subarray.get(j)
!= subarray.get(m - j - 1 )) {
is_palindrome = false ;
break ;
}
}
if (is_palindrome) {
result.add(subarray);
}
}
}
return result;
}
public static void main(String[] args)
{
Node head = new Node( 1 );
head.next = new Node( 2 );
head.next.next = new Node( 3 );
head.next.next.next = new Node( 4 );
head.next.next.next.next = new Node( 3 );
head.next.next.next.next.next = new Node( 2 );
head.next.next.next.next.next.next = new Node( 1 );
List<List<Integer> > result
= palindromicSubarrays(head);
for (List<Integer> subarray : result) {
for ( int num : subarray) {
System.out.print(num + " " );
}
System.out.println();
}
}
}
|
Python3
from typing import List
class Node:
def __init__( self , v):
self .val = v
self . next = None
def palindromicSubarrays(head: Node) - > List [ List [ int ]]:
result = []
arr = []
curr = head
while curr is not None :
arr.append(curr.val)
curr = curr. next
n = len (arr)
for k in range ( 2 , n + 1 ):
for i in range (n - k + 1 ):
subarray = arr[i:i + k]
if subarray = = subarray[:: - 1 ]:
result.append(subarray)
return result
head = Node( 1 )
head. next = Node( 2 )
head. next . next = Node( 3 )
head. next . next . next = Node( 4 )
head. next . next . next . next = Node( 3 )
head. next . next . next . next . next = Node( 2 )
head. next . next . next . next . next . next = Node( 1 )
result = palindromicSubarrays(head)
for subarray in result:
for num in subarray:
print (num, end = " " )
print ()
|
C#
using System;
using System.Collections.Generic;
public class Node {
public int val;
public Node next;
public Node( int v)
{
val = v;
next = null ;
}
}
public class Program {
public static List<List< int > >
PalindromicSubarrays(Node head)
{
List<List< int > > result = new List<List< int > >();
List< int > arr = new List< int >();
Node curr = head;
while (curr != null ) {
arr.Add(curr.val);
curr = curr.next;
}
int n = arr.Count;
for ( int k = 2; k <= n; k++) {
for ( int i = 0; i <= n - k; i++) {
List< int > subarray = new List< int >();
for ( int j = i; j < i + k; j++) {
subarray.Add(arr[j]);
}
bool isPalindrome = true ;
int m = subarray.Count;
for ( int j = 0; j < m / 2; j++) {
if (subarray[j]
!= subarray[m - j - 1]) {
isPalindrome = false ;
break ;
}
}
if (isPalindrome) {
result.Add(subarray);
}
}
}
return result;
}
public static void Main()
{
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(3);
head.next.next.next.next.next = new Node(2);
head.next.next.next.next.next.next = new Node(1);
List<List< int > > result
= PalindromicSubarrays(head);
foreach (List< int > subarray in result)
{
foreach ( int num in subarray)
{
Console.Write(num + " " );
}
Console.WriteLine();
}
}
}
|
Javascript
class Node {
constructor(v) {
this .val = v;
this .next = null ;
}
}
function palindromicSubarrays(head) {
let result = [];
let arr = [];
let curr = head;
while (curr) {
arr.push(curr.val);
curr = curr.next;
}
let n = arr.length;
for (let k = 2; k <= n; k++) {
for (let i = 0; i <= n - k; i++) {
let subarray = [];
for (let j = i; j < i + k; j++) {
subarray.push(arr[j]);
}
let is_palindrome = true ;
let m = subarray.length;
for (let j = 0; j < Math.floor(m / 2); j++) {
if (subarray[j] !== subarray[m - j - 1]) {
is_palindrome = false ;
break ;
}
}
if (is_palindrome) {
result.push(subarray);
}
}
}
return result;
}
let head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(3);
head.next.next.next.next.next = new Node(2);
head.next.next.next.next.next.next = new Node(1);
let result = palindromicSubarrays(head);
for (let subarray of result) {
console.log(subarray.join( " " ));
}
|
Output
3 4 3
2 3 4 3 2
1 2 3 4 3 2 1
Time Complexity: O(n^3)
Auxiliary Space: O(n^2)
Approach (Two Pointers technique): Convert the linked list to an array. Then, we iterate over each element in the array and check for palindromic subarrays using two pointers approach.
Algorithm steps:
- Create a Node class with a value and a pointer to the next node.
- Define a function palindromicSubarrays that takes a head pointer to a linked list as input and returns a vector of vectors of integers.
- Inside the function, initialize an empty vector of integers called arr, and a pointer curr to the head of the linked list.
- Traverse the linked list with curr and append each node’s value to the arr vector.
- Get the size of the arr vector and initialize an empty vector of vectors of integers called result.
- Iterate through all possible subarray lengths k from 2 to the length of the arr vector, and then for each length k, iterate through all possible starting positions i from 0 to n – k.
- For each subarray of length k starting at position i, create a subarray vector by appending the values of arr from index i to index i + k – 1.
- Check if the subarray vector is a palindrome by comparing the first half of the vector to the second half in reverse order.
- If the subarray is a palindrome, append it to the result vector.
- After iterating through all subarray lengths and positions, return the result vector.
Below is the implementation of the approach:
C++
#include <iostream>
#include <vector>
using namespace std;
class Node {
public :
int val;
Node* next;
Node( int v)
{
val = v;
next = NULL;
}
};
vector< int > toArray(Node* head) {
vector< int > arr;
Node* curr = head;
while (curr) {
arr.push_back(curr->val);
curr = curr->next;
}
return arr;
}
vector<vector< int >> palindromicSubarrays(Node* head) {
vector<vector< int >> result;
vector< int > arr = toArray(head);
int n = arr.size();
for ( int center = 0; center < n; center++) {
int left = center - 1;
int right = center + 1;
while (left >= 0 && right < n && arr[left] == arr[right]) {
result.push_back(vector< int >(arr.begin() + left, arr.begin() + right + 1));
left--;
right++;
}
left = center;
right = center + 1;
while (left >= 0 && right < n && arr[left] == arr[right]) {
result.push_back(vector< int >(arr.begin() + left, arr.begin() + right + 1));
left--;
right++;
}
}
return result;
}
int main()
{
Node* head = new Node(1);
head->next = new Node(2);
head->next->next = new Node(3);
head->next->next->next = new Node(4);
head->next->next->next->next = new Node(3);
head->next->next->next->next->next = new Node(2);
head->next->next->next->next->next->next = new Node(1);
vector<vector< int >> result = palindromicSubarrays(head);
for ( auto subarray : result) {
for ( auto num : subarray) {
cout << num << " " ;
}
cout << endl;
}
return 0;
}
|
Java
import java.util.ArrayList;
import java.util.List;
public class PalindromicSubarrays {
static class Node {
int val;
Node next;
Node( int v) {
val = v;
next = null ;
}
}
static List<List<Integer>> palindromicSubarrays(Node head) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> arr = toArray(head);
int n = arr.size();
for ( int center = 0 ; center < n; center++) {
int left = center - 1 ;
int right = center + 1 ;
while (left >= 0 && right < n && arr.get(left) == arr.get(right)) {
List<Integer> subarray = new ArrayList<>(arr.subList(left, right + 1 ));
result.add(subarray);
left--;
right++;
}
left = center;
right = center + 1 ;
while (left >= 0 && right < n && arr.get(left) == arr.get(right)) {
List<Integer> subarray = new ArrayList<>(arr.subList(left, right + 1 ));
result.add(subarray);
left--;
right++;
}
}
return result;
}
static List<Integer> toArray(Node head) {
List<Integer> arr = new ArrayList<>();
Node curr = head;
while (curr != null ) {
arr.add(curr.val);
curr = curr.next;
}
return arr;
}
public static void main(String[] args) {
Node head = new Node( 1 );
head.next = new Node( 2 );
head.next.next = new Node( 3 );
head.next.next.next = new Node( 4 );
head.next.next.next.next = new Node( 3 );
head.next.next.next.next.next = new Node( 2 );
head.next.next.next.next.next.next = new Node( 1 );
List<List<Integer>> result = palindromicSubarrays(head);
for (List<Integer> subarray : result) {
for ( int num : subarray) {
System.out.print(num + " " );
}
System.out.println();
}
}
}
|
Python3
class Node:
def __init__( self , v):
self .val = v
self . next = None
def to_array(head):
arr = []
curr = head
while curr:
arr.append(curr.val)
curr = curr. next
return arr
def palindromic_subarrays(head):
result = []
arr = to_array(head)
n = len (arr)
for center in range (n):
left = center - 1
right = center + 1
while left > = 0 and right < n and arr[left] = = arr[right]:
result.append(arr[left:right + 1 ])
left - = 1
right + = 1
left = center
right = center + 1
while left > = 0 and right < n and arr[left] = = arr[right]:
result.append(arr[left:right + 1 ])
left - = 1
right + = 1
return result
if __name__ = = "__main__" :
head = Node( 1 )
head. next = Node( 2 )
head. next . next = Node( 3 )
head. next . next . next = Node( 4 )
head. next . next . next . next = Node( 3 )
head. next . next . next . next . next = Node( 2 )
head. next . next . next . next . next . next = Node( 1 )
result = palindromic_subarrays(head)
for subarray in result:
print ( ' ' .join( str (num) for num in subarray))
|
C#
using System;
using System.Collections.Generic;
public class PalindromicSubarrays
{
public class Node
{
public int val;
public Node next;
public Node( int v)
{
val = v;
next = null ;
}
}
static List<List< int >> PalindromicSubarraysFunc(Node head)
{
List<List< int >> result = new List<List< int >>();
List< int > arr = ToArray(head);
int n = arr.Count;
for ( int center = 0; center < n; center++)
{
int left = center - 1;
int right = center + 1;
while (left >= 0 && right < n && arr[left] == arr[right])
{
List< int > subarray = new List< int >(arr.GetRange(left, right - left + 1));
result.Add(subarray);
left--;
right++;
}
left = center;
right = center + 1;
while (left >= 0 && right < n && arr[left] == arr[right])
{
List< int > subarray = new List< int >(arr.GetRange(left, right - left + 1));
result.Add(subarray);
left--;
right++;
}
}
return result;
}
static List< int > ToArray(Node head)
{
List< int > arr = new List< int >();
Node curr = head;
while (curr != null )
{
arr.Add(curr.val);
curr = curr.next;
}
return arr;
}
public static void Main( string [] args)
{
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(3);
head.next.next.next.next.next = new Node(2);
head.next.next.next.next.next.next = new Node(1);
List<List< int >> result = PalindromicSubarraysFunc(head);
foreach (List< int > subarray in result)
{
foreach ( int num in subarray)
{
Console.Write(num + " " );
}
Console.WriteLine();
}
}
}
|
Javascript
class Node {
constructor(v) {
this .val = v;
this .next = null ;
}
}
function toArray(head) {
let arr = [];
let curr = head;
while (curr) {
arr.push(curr.val);
curr = curr.next;
}
return arr;
}
function palindromicSubarrays(head) {
let result = [];
let arr = toArray(head);
let n = arr.length;
for (let center = 0; center < n; center++) {
let left = center - 1;
let right = center + 1;
while (left >= 0 && right < n && arr[left] === arr[right]) {
result.push(arr.slice(left, right + 1));
left--;
right++;
}
left = center;
right = center + 1;
while (left >= 0 && right < n && arr[left] === arr[right]) {
result.push(arr.slice(left, right + 1));
left--;
right++;
}
}
return result;
}
let head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(3);
head.next.next.next.next.next = new Node(2);
head.next.next.next.next.next.next = new Node(1);
let result = palindromicSubarrays(head);
for (let subarray of result) {
let temp = '' ;
for (let num of subarray) {
temp += num + " " ;
}
console.log(temp)
console.log( "\n" );
}
|
Output
3 4 3
2 3 4 3 2
1 2 3 4 3 2 1
Time Complexity: O(n^3), where n is the length of the linked list.
Auxiliary Space: O(n^2), where n is the length of the linked list.
Share your thoughts in the comments
Please Login to comment...