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++
// C++ Implementation of above approach
#include <iostream>
#include <vector>
using namespace std;
// Classification of node
class Node {
public:
int val;
Node* next;
Node(int v)
{
val = v;
next = NULL;
}
};
// Function to find all
// palindromic subarrays
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();
// Start Iterating from index 2
for (int k = 2; k <= n; k++) {
for (int i = 0; i <= n - k; i++) {
// If subarray is palindrome
vector<int> subarray;
for (int j = i; j < i + k; j++) {
subarray.push_back(arr[j]);
}
bool is_palindrome = true;
int m = subarray.size();
// To check for palindrome
for (int j = 0; j < m / 2; j++) {
if (subarray[j] != subarray[m - j - 1]) {
is_palindrome = false;
break;
}
}
// If subarray is palindrome
if (is_palindrome) {
result.push_back(subarray);
}
}
}
return result;
}
// Driver code
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);
// Function call
vector<vector<int> > result
= palindromicSubarrays(head);
// Print the vector present
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();
// Start Iterating from index 2
for (int k = 2; k <= n; k++) {
for (int i = 0; i <= n - k; i++) {
// If subarray is palindrome
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();
// To check for palindrome
for (int j = 0; j < m / 2; j++) {
if (subarray.get(j)
!= subarray.get(m - j - 1)) {
is_palindrome = false;
break;
}
}
// If subarray is palindrome
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);
// Function call
List<List<Integer> > result
= palindromicSubarrays(head);
// Print the vector present
for (List<Integer> subarray : result) {
for (int num : subarray) {
System.out.print(num + " ");
}
System.out.println();
}
}
}
// This code is contributed by omkar chavan
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)
# Start Iterating from index 2
for k in range(2, n + 1):
for i in range(n - k + 1):
# If subarray is palindrome
subarray = arr[i:i+k]
if subarray == subarray[::-1]:
result.append(subarray)
return result
# Driver code
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)
# Function call
result = palindromicSubarrays(head)
# Print the list present
for subarray in result:
for num in subarray:
print(num, end=" ")
print()
# This code is contributed by Vikas Bishnoi
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
// JavaScript implementation of above approach
// Classification of node
class Node {
constructor(v) {
this.val = v;
this.next = null;
}
}
// Function to find all
// palindromic subarrays
function palindromicSubarrays(head) {
let result = [];
let arr = [];
let curr = head;
while (curr) {
arr.push(curr.val);
curr = curr.next;
}
let n = arr.length;
// Start Iterating from index 2
for (let k = 2; k <= n; k++) {
for (let i = 0; i <= n - k; i++) {
// If subarray is palindrome
let subarray = [];
for (let j = i; j < i + k; j++) {
subarray.push(arr[j]);
}
let is_palindrome = true;
let m = subarray.length;
// To check for palindrome
for (let j = 0; j < Math.floor(m / 2); j++) {
if (subarray[j] !== subarray[m - j - 1]) {
is_palindrome = false;
break;
}
}
// If subarray is palindrome
if (is_palindrome) {
result.push(subarray);
}
}
}
return result;
}
// Driver code
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);
// Function call
let result = palindromicSubarrays(head);
// Print the vector present
for (let subarray of result) {
console.log(subarray.join(" "));
}
//This code is contributed by Tushar Rokade
Output3 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++
//C++ code for the above approach
#include <iostream>
#include <vector>
using namespace std;
// Classification of node
class Node {
public:
int val;
Node* next;
Node(int v)
{
val = v;
next = NULL;
}
};
// Function to convert linked list to array
vector<int> toArray(Node* head) {
vector<int> arr;
Node* curr = head;
while (curr) {
arr.push_back(curr->val);
curr = curr->next;
}
return arr;
}
// Function to find all palindromic subarrays
vector<vector<int>> palindromicSubarrays(Node* head) {
vector<vector<int>> result;
vector<int> arr = toArray(head);
int n = arr.size();
// Iterate over each element as center of palindromic subarray
for (int center = 0; center < n; center++) {
int left = center - 1;
int right = center + 1;
// Check for odd length palindromic subarray
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;
// Check for even length palindromic subarray
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;
}
// Driver code
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);
// Function call
vector<vector<int>> result = palindromicSubarrays(head);
// Print the vector present
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;
}
}
// Function to find all palindromic subarrays
static List<List<Integer>> palindromicSubarrays(Node head) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> arr = toArray(head);
int n = arr.size();
// Loop through each element as the potential center of the palindrome
for (int center = 0; center < n; center++) {
int left = center - 1;
int right = center + 1;
// Check for odd-length palindromes with center at 'center'
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++;
}
// Check for even-length palindromes with center at 'center' and 'center+1'
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;
}
// Function to convert linked list to an ArrayList
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) {
// Creating a linked list: 1 -> 2 -> 3 -> 4 -> 3 -> 2 -> 1
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);
// Find all palindromic subarrays and print the results
List<List<Integer>> result = palindromicSubarrays(head);
for (List<Integer> subarray : result) {
for (int num : subarray) {
System.out.print(num + " ");
}
System.out.println();
}
}
}
Python3
# Classification of node
class Node:
def __init__(self, v):
self.val = v
self.next = None
# Function to convert linked list to array
def to_array(head):
arr = []
curr = head
while curr:
arr.append(curr.val)
curr = curr.next
return arr
# Function to find all palindromic subarrays
def palindromic_subarrays(head):
result = []
arr = to_array(head)
n = len(arr)
# Iterate over each element as center of palindromic subarray
for center in range(n):
left = center - 1
right = center + 1
# Check for odd length palindromic subarray
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
# Check for even length palindromic subarray
while left >= 0 and right < n and arr[left] == arr[right]:
result.append(arr[left:right + 1])
left -= 1
right += 1
return result
# Driver code
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)
# Function call
result = palindromic_subarrays(head)
# Print the list of subarrays
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;
}
}
// Function to find all palindromic subarrays
static List<List<int>> PalindromicSubarraysFunc(Node head)
{
List<List<int>> result = new List<List<int>>();
List<int> arr = ToArray(head);
int n = arr.Count;
// Loop through each element as the potential center of the palindrome
for (int center = 0; center < n; center++)
{
int left = center - 1;
int right = center + 1;
// Check for odd-length palindromes with center at 'center'
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++;
}
// Check for even-length palindromes with center at 'center' and 'center+1'
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;
}
// Function to convert linked list to a List
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)
{
// Creating a linked list: 1 -> 2 -> 3 -> 4 -> 3 -> 2 -> 1
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);
// Find all palindromic subarrays and print the results
List<List<int>> result = PalindromicSubarraysFunc(head);
foreach (List<int> subarray in result)
{
foreach (int num in subarray)
{
Console.Write(num + " ");
}
Console.WriteLine();
}
}
}
JavaScript
// Classification of node
class Node {
constructor(v) {
this.val = v;
this.next = null;
}
}
// Function to convert linked list to array
function toArray(head) {
let arr = [];
let curr = head;
while (curr) {
arr.push(curr.val);
curr = curr.next;
}
return arr;
}
// Function to find all palindromic subarrays
function palindromicSubarrays(head) {
let result = [];
let arr = toArray(head);
let n = arr.length;
// Iterate over each element as center of palindromic subarray
for (let center = 0; center < n; center++) {
let left = center - 1;
let right = center + 1;
// Check for odd length palindromic subarray
while (left >= 0 && right < n && arr[left] === arr[right]) {
result.push(arr.slice(left, right + 1));
left--;
right++;
}
left = center;
right = center + 1;
// Check for even length palindromic subarray
while (left >= 0 && right < n && arr[left] === arr[right]) {
result.push(arr.slice(left, right + 1));
left--;
right++;
}
}
return result;
}
// Driver code
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");
}
Output3 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.
Similar Reads
Palindrome Linked List
Given a singly linked list. The task is to check if the given linked list is palindrome or not. Examples: Input: Output: trueExplanation: The given linked list is 1->2->1->1->2->1 , which is a palindrome and Hence, the output is true. Input: Output: falseExplanation: The given linked
15+ min read
Check if a linked list of strings forms a palindrome
Given a linked list handling string data, check to see whether data is palindrome or not? For example, Input : a -> bc -> d -> dcb -> a -> NULL Output : True String "abcddcba" is palindrome. Output : a -> bc -> d -> ba -> NULL Output : False String "abcdba" is not palindro
6 min read
Count Zero filled Subarrays in a Binary Linked list
Given a binary linked list that consists of the 1s and 0s nodes, the task is to find the number of zero-filled subarrays in the linked list. A zero-filled subarray is a contiguous subarray of nodes containing all zeroes. Examples: Input: List = 1->0->1->0->0->1->0Output: 5Explanati
12 min read
Check if sum of any subarray is Palindrome or not
Given an array arr[] of size N. the task is to check whether there exists any subarray of size atleast 2 such that its sum is palindrome. If such a subarray exists, then print YES. Otherwise, print NO.Examples: Input: arr[] = {10, 6, 7, 9, 12} Output: Yes Explanation: The subarray [6, 7, 9] with sum
8 min read
Find first node of loop in a linked list
Given the head of a linked list that may contain a loop. A loop means that the last node of the linked list is connected back to a node in the same list. The task is to find the Starting node of the loop in the linked list if there is no loop in the linked list return -1. Example: Input: Output: 3Ex
14 min read
Find extra node in the second Linked list
Given two Linked list L1 and L2. The second list L2 contains all the nodes of L1 along with 1 extra node. The task is to find that extra node. Examples: Input: L1 = 17 -> 7 -> 6 -> 16 L2 = 17 -> 7 -> 6 -> 16 -> 15 Output: 15 Explanation: Element 15 is not present in the L1 listI
7 min read
Find pairs with given sum in doubly linked list
Given a sorted doubly linked list of positive distinct elements, the task is to find pairs in a doubly-linked list whose sum is equal to the given value x in sorted order. Examples: Input: Output: (1, 6), (2,5)Explanation: We can see that there are two pairs (1, 6) and (2, 5) with sum 7. Input: Outp
14 min read
Counting inversions in an subarrays
Given an array arr[], the goal is to count the number of inversions in all the sub-arrays. An inversion is a pair of indices i and j such that i > j and arr[i] < arr[j]. A sub-array from index x to y ( x<= y) consists of the element's arr[x], arr[x+1], ..., arr[y]. The array arr[] can also
15+ min read
Sum of all Palindrome Numbers present in a Linked list
Given a linked list with integer node values, the task is to find the sum of all Palindrome Numbers present as Node values.Examples: Input: 13 -> 212 -> 22 -> 44 -> 4 -> 3 Output: 285 Explanation: The sum of palindrome numbers {22, 212, 44, 4, 3} is 285Input: 19 -> 22 -> 141 Out
8 min read
Number of palindromic paths in a matrix
Given a matrix containing lower alphabetical characters only, we need to count number of palindromic paths in given matrix. A path is defined as a sequence of cells starting from top-left cell and ending at bottom-right cell. We are allowed to move to right and down only from current cell. Examples:
13 min read