Find quadruplets with given sum in a Doubly Linked List
Last Updated :
23 Jul, 2025
Given a sorted doubly linked list and an integer X, the task is to print all the quadruplets in the doubly linked list whose sum is X.
Examples:
Input: LL: -3 ? 1 ? 2 ? 3 ? 5 ? 6, X = 7
Output:
-3 2 3 5
-3 3 1 6
Explanation: The quadruplets having sum 7( = X) are: {-3, 2, 3, 5}, {-3, 3, 1, 6}.
Input: LL: -2 ? -1 ? 0 ? 0 ? 1 ? 2, X = 0
Output:
-2 -1 1 2
-2 0 0 2
-1 0 0 1
Approach: The given problem can be solved by using the idea discussed in this article using the 4 pointer technique. Follow the steps below to solve the problem:
- Initialize four variables, say first as the start of the doubly linked list i.e.; first = head, second to the next of the first pointer, third to the next of second pointer, and fourth to the last node of a doubly linked list that stores all the 4 elements in the sorted doubly linked list.
- Iterate a loop until the first node and the fourth node is not NULL, and they are not equal and these 2 nodes do not cross each other and perform the following steps:
- Initialize the second pointer to the next of the first.
- Iterate a loop until the second and fourth nodes are not NULL, they are not equal and do not cross each other.
- Initialize a variable, say sum as (X - (first?data + second?data)), point the third pointer to the next of second pointer, and take another temp pointer initialized to the last node i.e., pointer fourth.
- Iterate a loop while temp and third are not NULL, they are not equal and do not cross each other
- If the value of the sum is third?data + temp?data, then print the quadruple and increment the third pointer to the next of current third pointer and temp to the previous of current temp.
- If the value of sum is less than the third?data + temp?data, then increment the third pointer, i.e., third = third?next.
- Otherwise, decrement the temp pointer i.e temp = temp?prev.
- Move the second pointer to its next pointer.
- Move the first pointer to its next pointer.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Structure of node of a doubly
// linked list
struct Node {
int data;
struct Node *next, *prev;
};
// Function to insert a new node at
// the beginning of the doubly linked
// list
void insert(struct Node** head, int data)
{
// Allocate the node
struct Node* temp = new Node();
// Fill in the data value
temp->data = data;
temp->next = temp->prev = NULL;
if ((*head) == NULL)
(*head) = temp;
else {
temp->next = *head;
(*head)->prev = temp;
(*head) = temp;
}
}
// Function to print the quadruples
// having sum equal to x
void PrintFourSum(struct Node* head, int x)
{
// First pointer to the head node
struct Node* first = head;
// Pointer to point to the second
// node for the required sum
struct Node* second;
// Pointer to point to the third
// node for the required sum
struct Node* third;
// Fourth points to the last node
struct Node* fourth = head;
// Update the fourth pointer to
// the end of the DLL
while (fourth->next != NULL) {
fourth = fourth->next;
}
// Node to point to the fourth node
// of the required sum
struct Node* temp;
while (first != NULL
&& fourth != NULL
&& first != fourth
&& fourth->next != first) {
// Point the second node to the
// second element of quadruple
second = first->next;
while (second != NULL
&& fourth != NULL
&& second != fourth
&& fourth->next != second) {
int reqsum = x - (first->data
+ second->data);
// Points to the 3rd element
// of quadruple
third = second->next;
// Points to the tail of the DLL
temp = fourth;
while (third != NULL && temp != NULL
&& third != temp
&& temp->next != third) {
// Store the current sum
int twosum = third->data
+ temp->data;
// If the sum is equal,
// then print quadruple
if (twosum == reqsum) {
cout << "(" << first->data
<< ", "
<< second->data
<< ", "
<< third->data
<< ", "
<< temp->data
<< ")\n";
third = third->next;
temp = temp->prev;
}
// If twosum is less than
// the reqsum then move the
// third pointer to the next
else if (twosum < reqsum) {
third = third->next;
}
// Otherwise move the fourth
// pointer to the previous
// of the fourth pointer
else {
temp = temp->prev;
}
}
// Move to the next of
// the second pointer
second = second->next;
}
// Move to the next of
// the first pointer
first = first->next;
}
}
// Driver Code
int main()
{
struct Node* head = NULL;
insert(&head, 2);
insert(&head, 1);
insert(&head, 0);
insert(&head, 0);
insert(&head, -1);
insert(&head, -2);
int X = 0;
PrintFourSum(head, X);
return 0;
}
Java
// Java program for the above approach
class GFG {
// structure of node of
// doubly linked list
static class Node {
int data;
Node next, prev;
};
// A utility function to insert
// a new node at the beginning
// of the doubly linked list
static Node insert(Node head, int data)
{
// Allocate the node
Node temp = new Node();
// Fill in the data value
temp.data = data;
temp.next = temp.prev = null;
if (head == null)
(head) = temp;
else {
temp.next = head;
(head).prev = temp;
(head) = temp;
}
return temp;
}
// Function to print the quadruples
// having sum equal to x
static void PrintFourSum(Node head, int x)
{
// First pointer to the head node
Node first = head;
// Pointer to point to the second
// node for the required sum
Node second = head;
// Pointer to point to the third
// node for the required sum
Node third = head;
// Fourth points to the last node
Node fourth = head;
// Update the fourth pointer to
// the end of the DLL
while (fourth.next != null) {
fourth = fourth.next;
}
// Node to point to the fourth node
// of the required sum
Node temp;
while (first != null && fourth != null
&& first != fourth && fourth.next != first) {
// Point the second node to the
// second element of quadruple
second = first.next;
while (second != null && fourth != null
&& second != fourth
&& fourth.next != second) {
int reqsum = x - (first.data + second.data);
// Points to the 3rd element
// of quadruple
third = second.next;
// Points to the tail of the DLL
temp = fourth;
while (third != null && temp != null
&& third != temp
&& temp.next != third) {
// Store the current sum
int twosum = third.data + temp.data;
// If the sum is equal,
// then print quadruple
if (twosum == reqsum) {
System.out.println(
"(" + first.data + ", "
+ second.data + ", "
+ third.data + ", " + temp.data
+ ")");
third = third.next;
temp = temp.prev;
}
// If twosum is less than
// the reqsum then move the
// third pointer to the next
else if (twosum < reqsum) {
third = third.next;
}
// Otherwise move the fourth
// pointer to the previous
// of the fourth pointer
else {
temp = temp.prev;
}
}
// Move to the next of
// the second pointer
second = second.next;
}
// Move to the next of
// the first pointer
first = first.next;
}
}
// Driver Code
public static void main(String args[])
{
Node head = null;
head = insert(head, 2);
head = insert(head, 1);
head = insert(head, 0);
head = insert(head, 0);
head = insert(head, -1);
head = insert(head, -2);
int x = 0;
PrintFourSum(head, x);
}
}
// This code is contributed
// by kirtishsurangalikar
Python3
# Python3 program for the above approach
# Structure of node of a doubly
# linked list
class Node:
def __init__(self, d):
self.data = d
self.left = None
self.right = None
# Function to insert a new node at
# the beginning of the doubly linked
# list
def insert(head, data):
# Allocate the node
temp = Node(data)
# Fill in the data value
temp.data = data
temp.next = temp.prev = None
if (head == None):
head = temp
else:
temp.next = head
head.prev = temp
head = temp
return head
# Function to print the quadruples
# having sum equal to x
def PrintFourSum(head, x):
# First pointer to the head node
first = head
# Pointer to point to the second
# node for the required sum
second = None
# Pointer to point to the third
# node for the required sum
third = None
# Fourth points to the last node
fourth = head
# Update the fourth pointer to
# the end of the DLL
while (fourth.next != None):
fourth = fourth.next
# Node to point to the fourth node
# of the required sum
temp = None
while (first != None and
fourth != None and
first != fourth and
fourth.next != first):
# Point the second node to the
# second element of quadruple
second = first.next
while (second != None and
fourth != None and
second != fourth and
fourth.next != second):
reqsum = x - (first.data +
second.data)
# Points to the 3rd element
# of quadruple
third = second.next
# Points to the tail of the DLL
temp = fourth
while (third != None and temp != None and
third != temp and temp.next != third):
# Store the current sum
twosum = third.data + temp.data
# If the sum is equal,
# then print quadruple
if (twosum == reqsum):
print("(" + str(first.data) +
", " + str(second.data) +
", " + str(third.data) +
", " + str(temp.data) + ")")
third = third.next
temp = temp.prev
# If twosum is less than
# the reqsum then move the
# third pointer to the next
elif (twosum < reqsum):
third = third.next
# Otherwise move the fourth
# pointer to the previous
# of the fourth pointer
else:
temp = temp.prev
# Move to the next of
# the second pointer
second = second.next
# Move to the next of
# the first pointer
first = first.next
# Driver Code
if __name__ == '__main__':
head = None
head = insert(head, 2)
head = insert(head, 1)
head = insert(head, 0)
head = insert(head, 0)
head = insert(head, -1)
head = insert(head, -2)
X = 0
PrintFourSum(head, X)
# This code is contributed by mohit kumar 29
C#
// C# program for the above approach
using System;
public class GFG {
// structure of node of
// doubly linked list
public class Node {
public int data;
public Node next, prev;
};
// A utility function to insert
// a new node at the beginning
// of the doubly linked list
static Node insert(Node head, int data) {
// Allocate the node
Node temp = new Node();
// Fill in the data value
temp.data = data;
temp.next = temp.prev = null;
if (head == null)
(head) = temp;
else {
temp.next = head;
(head).prev = temp;
(head) = temp;
}
return temp;
}
// Function to print the quadruples
// having sum equal to x
static void PrintFourSum(Node head, int x) {
// First pointer to the head node
Node first = head;
// Pointer to point to the second
// node for the required sum
Node second = head;
// Pointer to point to the third
// node for the required sum
Node third = head;
// Fourth points to the last node
Node fourth = head;
// Update the fourth pointer to
// the end of the DLL
while (fourth.next != null) {
fourth = fourth.next;
}
// Node to point to the fourth node
// of the required sum
Node temp;
while (first != null && fourth != null && first != fourth && fourth.next != first) {
// Point the second node to the
// second element of quadruple
second = first.next;
while (second != null && fourth != null && second != fourth && fourth.next != second) {
int reqsum = x - (first.data + second.data);
// Points to the 3rd element
// of quadruple
third = second.next;
// Points to the tail of the DLL
temp = fourth;
while (third != null && temp != null && third != temp && temp.next != third) {
// Store the current sum
int twosum = third.data + temp.data;
// If the sum is equal,
// then print quadruple
if (twosum == reqsum) {
Console.WriteLine(
"(" + first.data + ", " + second.data + ", " + third.data + ", " + temp.data + ")");
third = third.next;
temp = temp.prev;
}
// If twosum is less than
// the reqsum then move the
// third pointer to the next
else if (twosum < reqsum) {
third = third.next;
}
// Otherwise move the fourth
// pointer to the previous
// of the fourth pointer
else {
temp = temp.prev;
}
}
// Move to the next of
// the second pointer
second = second.next;
}
// Move to the next of
// the first pointer
first = first.next;
}
}
// Driver Code
public static void Main(String []args) {
Node head = null;
head = insert(head, 2);
head = insert(head, 1);
head = insert(head, 0);
head = insert(head, 0);
head = insert(head, -1);
head = insert(head, -2);
int x = 0;
PrintFourSum(head, x);
}
}
// This code is contributed by gauravrajput1
JavaScript
<script>
// Javascript program for the above approach
// Structure of node of a doubly
// linked list
class Node {
constructor()
{
this.data = 0;
this.next = null;
this.prev = null;
}
};
// Function to insert a new node at
// the beginning of the doubly linked
// list
function insert(head, data)
{
// Allocate the node
var temp = new Node();
// Fill in the data value
temp.data = data;
temp.next = temp.prev = null;
if ((head) == null)
(head) = temp;
else {
temp.next = head;
(head).prev = temp;
(head) = temp;
}
return head;
}
// Function to print the quadruples
// having sum equal to x
function PrintFourSum(head, x)
{
// First pointer to the head node
var first = head;
// Pointer to point to the second
// node for the required sum
var second;
// Pointer to point to the third
// node for the required sum
var third;
// Fourth points to the last node
var fourth = head;
// Update the fourth pointer to
// the end of the DLL
while (fourth.next != null) {
fourth = fourth.next;
}
// Node to point to the fourth node
// of the required sum
var temp;
while (first != null
&& fourth != null
&& first != fourth
&& fourth.next != first) {
// Point the second node to the
// second element of quadruple
second = first.next;
while (second != null
&& fourth != null
&& second != fourth
&& fourth.next != second) {
var reqsum = x - (first.data
+ second.data);
// Points to the 3rd element
// of quadruple
third = second.next;
// Points to the tail of the DLL
temp = fourth;
while (third != null && temp != null
&& third != temp
&& temp.next != third) {
// Store the current sum
var twosum = third.data
+ temp.data;
// If the sum is equal,
// then print quadruple
if (twosum == reqsum) {
document.write( "(" + first.data
+ ", "
+ second.data
+ ", "
+ third.data
+ ", "
+ temp.data
+ ")<br>");
third = third.next;
temp = temp.prev;
}
// If twosum is less than
// the reqsum then move the
// third pointer to the next
else if (twosum < reqsum) {
third = third.next;
}
// Otherwise move the fourth
// pointer to the previous
// of the fourth pointer
else {
temp = temp.prev;
}
}
// Move to the next of
// the second pointer
second = second.next;
}
// Move to the next of
// the first pointer
first = first.next;
}
}
// Driver Code
var head = null;
head = insert(head, 2);
head = insert(head, 1);
head = insert(head, 0);
head = insert(head, 0);
head = insert(head, -1);
head = insert(head, -2);
var X = 0;
PrintFourSum(head, X);
// This code is contributed by rrrtnx.
</script>
Output(-2, -1, 1, 2)
(-2, 0, 0, 2)
(-1, 0, 0, 1)
Time Complexity: O(N3)
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem