Print duplicates from a list of integers
Last Updated :
02 Nov, 2023
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++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
};
void insert(Node** head, int item)
{
Node* temp = new Node();
temp->data = item;
temp->next = *head;
*head = temp;
}
vector< int > printDuplicatesInList(Node* head)
{
vector< int > dupes;
while (head->next != NULL) {
Node* ptr = head->next;
while (ptr != NULL) {
if (head->data == ptr->data) {
dupes.push_back(head->data);
break ;
}
ptr = ptr->next;
}
head = head->next;
}
return dupes;
}
int main()
{
Node* head = NULL;
insert(&head, 5);
insert(&head, 7);
insert(&head, 5);
insert(&head, 1);
insert(&head, 7);
vector< int > dupesInList = printDuplicatesInList(head);
for ( int i = 0; i < dupesInList.size(); i++)
cout << dupesInList[i] << ", " ;
cout << endl;
return 0;
}
|
Java
import java.util.*;
class Node {
int data;
Node next;
}
public class PrintDuplicateNodes {
static void insert(Node[] head, int item) {
Node temp = new Node();
temp.data = item;
temp.next = head[ 0 ];
head[ 0 ] = temp;
}
static List<Integer> printDuplicatesInList(Node head) {
List<Integer> dupes = new ArrayList<>();
while (head.next != null ) {
Node ptr = head.next;
while (ptr != null ) {
if (head.data == ptr.data) {
dupes.add(head.data);
break ;
}
ptr = ptr.next;
}
head = head.next;
}
return dupes;
}
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 );
List<Integer> dupesInList = printDuplicatesInList(head[ 0 ]);
for ( int i = 0 ; i < dupesInList.size(); i++) {
System.out.print(dupesInList.get(i) + ", " );
}
System.out.println();
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self . next = None
def insert(head, item):
new_node = Node(item)
new_node. next = head
head = new_node
return head
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
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 )
dupes_in_list = print_duplicates_in_list(head)
for item in dupes_in_list:
print (item, end = ", " )
print ()
|
C#
using System;
using System.Collections.Generic;
class Node
{
public int data;
public Node next;
}
class Program
{
static void Insert( ref Node head, int item)
{
Node temp = new Node
{
data = item,
next = head
};
head = temp;
}
static List< int > PrintDuplicatesInList(Node head)
{
List< int > dupes = new List< int >();
while (head.next != null )
{
Node ptr = head.next;
while (ptr != null )
{
if (head.data == ptr.data)
{
dupes.Add(head.data);
break ;
}
ptr = ptr.next;
}
head = head.next;
}
return dupes;
}
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);
List< int > dupesInList = PrintDuplicatesInList(head);
foreach ( int item in dupesInList)
{
Console.Write(item + ", " );
}
Console.WriteLine();
}
}
|
Javascript
class Node {
constructor(data) {
this .data = data;
this .next = null ;
}
}
function insert(head, item) {
const temp = new Node(item);
temp.next = head[0];
head[0] = temp;
}
function printDuplicatesInList(head) {
const dupes = [];
while (head.next !== null ) {
let ptr = head.next;
while (ptr !== null ) {
if (head.data === ptr.data) {
dupes.push(head.data);
break ;
}
ptr = ptr.next;
}
head = head.next;
}
return dupes;
}
const head = [ null ];
insert(head, 5);
insert(head, 7);
insert(head, 5);
insert(head, 1);
insert(head, 7);
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++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
};
void insert(Node** head, int item)
{
Node* temp = new Node();
temp->data = item;
temp->next = *head;
*head = temp;
}
map< int , int > printDuplicatesInList(Node* head)
{
map< int , int > M;
int count = 0;
for (Node* curr = head; curr != NULL;
curr = curr->next) {
if (M.find(curr->data) == M.end())
M[curr->data] = 1;
else
M[curr->data]++;
}
return M;
}
int main()
{
Node* head = NULL;
insert(&head, 5);
insert(&head, 7);
insert(&head, 5);
insert(&head, 1);
insert(&head, 7);
map< int , int > dupesInList = printDuplicatesInList(head);
for ( auto & it : dupesInList) {
if (it.second > 1)
cout << it.first << ", " ;
}
cout << endl;
return 0;
}
|
Java
import java.util.*;
class Node {
int data;
Node next;
}
public class PrintDuplicateNodes {
static void insert(Node[] head, int item) {
Node temp = new Node();
temp.data = item;
temp.next = head[ 0 ];
head[ 0 ] = temp;
}
static Map<Integer, Integer> printDuplicatesInList(Node head) {
Map<Integer, Integer> M = new HashMap<>();
Node curr = head;
while (curr != null ) {
if (!M.containsKey(curr.data)) {
M.put(curr.data, 1 );
}
else {
M.put(curr.data, M.get(curr.data) + 1 );
}
curr = curr.next;
}
return M;
}
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 );
Map<Integer, Integer> dupesInList = printDuplicatesInList(head[ 0 ]);
for (Map.Entry<Integer, Integer> entry : dupesInList.entrySet()) {
if (entry.getValue() > 1 ) {
System.out.print(entry.getKey() + ", " );
}
}
System.out.println();
}
}
|
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 = {}
curr = head
while curr is not None :
if curr.data not in M:
M[curr.data] = 1
else :
M[curr.data] + = 1
curr = curr. next
return M
head = [ None ]
insert(head, 5 )
insert(head, 7 )
insert(head, 5 )
insert(head, 1 )
insert(head, 7 )
dupes_in_list = print_duplicates_in_list(head[ 0 ])
for key, value in dupes_in_list.items():
if value > 1 :
print (key, end = ", " )
print ()
|
C#
using System;
using System.Collections.Generic;
class Node
{
public int data;
public Node next;
}
class Program
{
static void Insert( ref Node head, int item)
{
Node temp = new Node
{
data = item,
next = head
};
head = temp;
}
static Dictionary< int , int > PrintDuplicatesInList(Node head)
{
Dictionary< int , int > M = new Dictionary< int , int >();
for (Node curr = head; curr != null ; curr = curr.next)
{
if (!M.ContainsKey(curr.data))
M[curr.data] = 1;
else
M[curr.data]++;
}
return M;
}
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);
Dictionary< int , int > dupesInList = PrintDuplicatesInList(head);
foreach ( var kvp in dupesInList)
{
if (kvp.Value > 1)
Console.Write(kvp.Key + ", " );
}
Console.WriteLine();
}
}
|
Javascript
class Node {
constructor(data) {
this .data = data;
this .next = null ;
}
}
function insert(head, item) {
const temp = new Node(item);
temp.next = head[0];
head[0] = temp;
}
function printDuplicatesInList(head) {
const frequencyMap = new Map();
let curr = head;
while (curr !== null ) {
if (!frequencyMap.has(curr.data)) {
frequencyMap.set(curr.data, 1);
}
else {
frequencyMap.set(curr.data, frequencyMap.get(curr.data) + 1);
}
curr = curr.next;
}
const duplicateKeys = [];
for (const [key, value] of frequencyMap.entries()) {
if (value > 1) {
duplicateKeys.push(key);
}
}
return duplicateKeys;
}
const head = [ null ];
insert(head, 5);
insert(head, 7);
insert(head, 5);
insert(head, 1);
insert(head, 7);
const duplicateKeys = printDuplicatesInList(head[0]);
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.
Share your thoughts in the comments
Please Login to comment...