Open In App

Find palindromic Subarrays in a Linked List

Last Updated : 14 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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

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++
//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");
    }

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. 


Next Article
Article Tags :
Practice Tags :

Similar Reads