Print duplicates from a list of integers
Last Updated :
23 Jul, 2025
Given a Linked list of integers containing duplicate elements, the task is to print all the duplicates in the given Linked List.
Examples:
Input: list = [10, 20, 30, 20, 20, 30, 40, 50, -20, 60, 60, -20, -20]
Output: [20, 30, -20, 60]
Input: list = [5, 7, 5, 1, 7]
Output: [5, 7]
Naive Approach: To basic way to solve the problem is as follows:
- We traverse the whole linked list.
- For each node, we check in the remaining list whether the duplicate node exists or not.
- If it does then store it in an array.
- In the end, print all elements of the array
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Representation of node
struct Node {
int data;
Node* next;
};
// Function to insert a node at the beginning
void insert(Node** head, int item)
{
Node* temp = new Node();
temp->data = item;
temp->next = *head;
*head = temp;
}
// Function to print duplicate nodes in
// the linked list
vector<int> printDuplicatesInList(Node* head)
{
vector<int> dupes;
while (head->next != NULL) {
// Starting from the next node
Node* ptr = head->next;
while (ptr != NULL) {
// If some duplicate node is found
if (head->data == ptr->data) {
dupes.push_back(head->data);
break;
}
ptr = ptr->next;
}
head = head->next;
}
// Return the count of duplicate nodes
return dupes;
}
// Driver code
int main()
{
Node* head = NULL;
insert(&head, 5);
insert(&head, 7);
insert(&head, 5);
insert(&head, 1);
insert(&head, 7);
// Function Call
vector<int> dupesInList = printDuplicatesInList(head);
for (int i = 0; i < dupesInList.size(); i++)
cout << dupesInList[i] << ", ";
cout << endl;
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
class Node {
int data;
Node next;
}
public class PrintDuplicateNodes {
// Function to insert a node at the beginning
static void insert(Node[] head, int item) {
Node temp = new Node();
temp.data = item;
temp.next = head[0];
head[0] = temp;
}
// Function to print duplicate nodes in the linked list
static List<Integer> printDuplicatesInList(Node head) {
List<Integer> dupes = new ArrayList<>();
while (head.next != null) {
// Starting from the next node
Node ptr = head.next;
while (ptr != null) {
// If some duplicate node is found
if (head.data == ptr.data) {
dupes.add(head.data);
break;
}
ptr = ptr.next;
}
head = head.next;
}
// Return the list of duplicate nodes
return dupes;
}
// Driver code
public static void main(String[] args) {
Node[] head = new Node[1];
head[0] = null;
insert(head, 5);
insert(head, 7);
insert(head, 5);
insert(head, 1);
insert(head, 7);
// Function Call
List<Integer> dupesInList = printDuplicatesInList(head[0]);
for (int i = 0; i < dupesInList.size(); i++) {
System.out.print(dupesInList.get(i) + ", ");
}
System.out.println();
}
}
//This code is contributed by chinmaya121221
Python3
# Representation of node
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Function to insert a node at the beginning
def insert(head, item):
new_node = Node(item)
new_node.next = head
head = new_node
return head
# Function to print duplicate nodes in the linked list
def print_duplicates_in_list(head):
dupes = []
while head is not None:
ptr = head.next
while ptr is not None:
if head.data == ptr.data:
dupes.append(head.data)
break
ptr = ptr.next
head = head.next
return dupes
# Driver code
if __name__ == "__main__":
head = None
head = insert(head, 5)
head = insert(head, 7)
head = insert(head, 5)
head = insert(head, 1)
head = insert(head, 7)
# Function call
dupes_in_list = print_duplicates_in_list(head)
for item in dupes_in_list:
print(item, end=", ")
print()
#Contributed by Aditi Tyagi
C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
// Representation of node
class Node
{
public int data;
public Node next;
}
class Program
{
// Function to insert a node at the beginning
static void Insert(ref Node head, int item)
{
Node temp = new Node
{
data = item,
next = head
};
head = temp;
}
// Function to print duplicate nodes in the linked list
static List<int> PrintDuplicatesInList(Node head)
{
List<int> dupes = new List<int>();
while (head.next != null)
{
// Starting from the next node
Node ptr = head.next;
while (ptr != null)
{
// If some duplicate node is found
if (head.data == ptr.data)
{
dupes.Add(head.data);
break;
}
ptr = ptr.next;
}
head = head.next;
}
// Return the count of duplicate nodes
return dupes;
}
// Driver code
static void Main(string[] args)
{
Node head = null;
Insert(ref head, 5);
Insert(ref head, 7);
Insert(ref head, 5);
Insert(ref head, 1);
Insert(ref head, 7);
// Function Call
List<int> dupesInList = PrintDuplicatesInList(head);
foreach (int item in dupesInList)
{
Console.Write(item + ", ");
}
Console.WriteLine();
}
}
// this code is contributed by uttamdp_10
JavaScript
// Define a class for the linked list node
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// Function to insert a node at the beginning of the linked list
function insert(head, item) {
const temp = new Node(item);
temp.next = head[0];
head[0] = temp;
}
// Function to print duplicate nodes in the linked list
function printDuplicatesInList(head) {
const dupes = [];
while (head.next !== null) {
// Starting from the next node
let ptr = head.next;
while (ptr !== null) {
// If some duplicate node is found
if (head.data === ptr.data) {
dupes.push(head.data);
break;
}
ptr = ptr.next;
}
head = head.next;
}
// Return the list of duplicate nodes
return dupes;
}
// Driver code
const head = [null];
insert(head, 5);
insert(head, 7);
insert(head, 5);
insert(head, 1);
insert(head, 7);
// Function Call
const dupesInList = printDuplicatesInList(head[0]);
for (let i = 0; i < dupesInList.length; i++) {
process.stdout.write(dupesInList[i] + ", ");
}
console.log();
Time Complexity: O(N2), where N is the number of elements in the list.
Auxiliary Space: O(N), an additional vector is used to store the duplicate values.
Printing duplicates from a list of integers using Hashing:
- We traverse the whole linked list.
- Create a hashtable
- For each node
- If it is not present in the hashtable, insert it with frequency 1
- If it is already present, update its frequency
- At the end, print all elements of the hashtable with frequency more than 1
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Representation of node
struct Node {
int data;
Node* next;
};
// Function to insert a node at the beginning
void insert(Node** head, int item)
{
Node* temp = new Node();
temp->data = item;
temp->next = *head;
*head = temp;
}
// Function to print duplicate nodes in
// the linked list
map<int, int> printDuplicatesInList(Node* head)
{
// Create a hash table insert head
map<int, int> M;
// Traverse through remaining nodes
int count = 0;
for (Node* curr = head; curr != NULL;
curr = curr->next) {
// If the current element
// is not found then insert
// current element with
// frequency 1
if (M.find(curr->data) == M.end())
M[curr->data] = 1;
// Else update the frequency
else
M[curr->data]++;
}
// Return the map with frequency
return M;
}
// Driver code
int main()
{
Node* head = NULL;
insert(&head, 5);
insert(&head, 7);
insert(&head, 5);
insert(&head, 1);
insert(&head, 7);
// Function Call
map<int, int> dupesInList = printDuplicatesInList(head);
// Traverse the map to print the
// frequency
for (auto& it : dupesInList) {
if (it.second > 1)
cout << it.first << ", ";
}
cout << endl;
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
class Node {
int data;
Node next;
}
public class PrintDuplicateNodes {
// Function to insert a node at the beginning
static void insert(Node[] head, int item) {
Node temp = new Node();
temp.data = item;
temp.next = head[0];
head[0] = temp;
}
// Function to print duplicate nodes in the linked list
static Map<Integer, Integer> printDuplicatesInList(Node head) {
Map<Integer, Integer> M = new HashMap<>();
// Traverse through remaining nodes
Node curr = head;
while (curr != null) {
// If the current element is not found then insert
// the current element with frequency 1
if (!M.containsKey(curr.data)) {
M.put(curr.data, 1);
}
// Else update the frequency
else {
M.put(curr.data, M.get(curr.data) + 1);
}
curr = curr.next;
}
// Return the map with frequency
return M;
}
// Driver code
public static void main(String[] args) {
Node[] head = new Node[1];
head[0] = null;
insert(head, 5);
insert(head, 7);
insert(head, 5);
insert(head, 1);
insert(head, 7);
// Function Call
Map<Integer, Integer> dupesInList = printDuplicatesInList(head[0]);
// Traverse the map to print the frequency
for (Map.Entry<Integer, Integer> entry : dupesInList.entrySet()) {
if (entry.getValue() > 1) {
System.out.print(entry.getKey() + ", ");
}
}
System.out.println();
}
}
//This code is contributed by chinmaya121221
Python3
class Node:
def __init__(self, data):
self.data = data
self.next = None
def insert(head, item):
temp = Node(item)
temp.next = head[0]
head[0] = temp
def print_duplicates_in_list(head):
M = {}
# Traverse through the linked list
curr = head
while curr is not None:
# If the current element is not found, insert it with frequency 1
if curr.data not in M:
M[curr.data] = 1
# Else update the frequency
else:
M[curr.data] += 1
curr = curr.next
# Return a dictionary with frequencies
return M
# Driver code
head = [None]
insert(head, 5)
insert(head, 7)
insert(head, 5)
insert(head, 1)
insert(head, 7)
# Function Call
dupes_in_list = print_duplicates_in_list(head[0])
# Traverse the dictionary to print elements with frequency > 1
for key, value in dupes_in_list.items():
if value > 1:
print(key, end=", ")
print()
C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
// Representation of node
class Node
{
public int data;
public Node next;
}
class Program
{
// Function to insert a node at the beginning
static void Insert(ref Node head, int item)
{
Node temp = new Node
{
data = item,
next = head
};
head = temp;
}
// Function to print duplicate nodes in the linked list
static Dictionary<int, int> PrintDuplicatesInList(Node head)
{
// Create a dictionary to insert head
Dictionary<int, int> M = new Dictionary<int, int>();
// Traverse through remaining nodes
for (Node curr = head; curr != null; curr = curr.next)
{
// If the current element is not found then insert
// current element with frequency 1
if (!M.ContainsKey(curr.data))
M[curr.data] = 1;
// Else update the frequency
else
M[curr.data]++;
}
// Return the dictionary with frequency
return M;
}
// Driver code
static void Main(string[] args)
{
Node head = null;
Insert(ref head, 5);
Insert(ref head, 7);
Insert(ref head, 5);
Insert(ref head, 1);
Insert(ref head, 7);
// Function Call
Dictionary<int, int> dupesInList = PrintDuplicatesInList(head);
// Traverse the dictionary to print the frequency
foreach (var kvp in dupesInList)
{
if (kvp.Value > 1)
Console.Write(kvp.Key + ", ");
}
Console.WriteLine();
}
}
// this code is contributed by uttamdp_10
JavaScript
// Define a class for the linked list node
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// Function to insert a node at the beginning of the linked list
function insert(head, item) {
// Create a new node with the given data
const temp = new Node(item);
// Set the next pointer of the new node to the current head
temp.next = head[0];
// Update the head to the new node
head[0] = temp;
}
// Function to find duplicate nodes in the linked list and their frequencies
function printDuplicatesInList(head) {
// Create a Map to store the frequency of each element
const frequencyMap = new Map();
let curr = head;
// Traverse through the linked list
while (curr !== null) {
// If the current element is not found in the Map, add it with a frequency of 1
if (!frequencyMap.has(curr.data)) {
frequencyMap.set(curr.data, 1);
}
// If the element already exists in the Map, update its frequency
else {
frequencyMap.set(curr.data, frequencyMap.get(curr.data) + 1);
}
curr = curr.next;
}
// Create an array to store the duplicate keys (elements with frequency > 1)
const duplicateKeys = [];
for (const [key, value] of frequencyMap.entries()) {
if (value > 1) {
duplicateKeys.push(key);
}
}
return duplicateKeys;
}
// Create the head of the linked list
const head = [null];
// Insert elements at the beginning of the linked list
insert(head, 5);
insert(head, 7);
insert(head, 5);
insert(head, 1);
insert(head, 7);
// Find and print duplicate keys in the linked list
const duplicateKeys = printDuplicatesInList(head[0]);
// Print the duplicate keys
for (let i = 0; i < duplicateKeys.length; i++) {
process.stdout.write(duplicateKeys[i] + ", ");
}
console.log();
Time Complexity: O(N*logN), for traversing the list O(N) time will consume, and to find the element in msp, O(Log N) time will be taken, So the time complexity of the above approach is O(N*logN).
Auxiliary Space: O(N), map is used to store the elements.
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