First non-repeating in a linked list
Last Updated :
24 Jul, 2023
Given a linked list, find its first non-repeating integer element.
Examples:
Input : 10->20->30->10->20->40->30->NULL
Output :First Non-repeating element is 40.
Input :1->1->2->2->3->4->3->4->5->NULL
Output :First Non-repeating element is 5.
Input :1->1->2->2->3->4->3->4->NULL
Output :No NOn-repeating element is found.
- Create a hash table and marked all elements as zero.
- Traverse the linked list and count the frequency of all the elements in the hashtable.
- Traverse the linked list again and see the element whose frequency is 1 in the hashtable.
Implementation:
C++
// C++ program to find first non-repeating
// element in a linked list
#include<bits/stdc++.h>
using namespace std;
/* Link list node */
struct Node
{
int data;
struct Node* next;
};
/* Function to find the first non-repeating
element in the linked list */
int firstNonRepeating(struct Node *head)
{
// Create an empty map and insert all linked
// list elements into hash table
unordered_map<int, int> mp;
for (Node *temp=head; temp!=NULL; temp=temp->next)
mp[temp->data]++;
// Traverse the linked list again and return
// the first node whose count is 1
for (Node *temp=head; temp!=NULL; temp=temp->next)
if (mp[temp->data] == 1)
return temp->data;
return -1;
}
/* Function to push a node */
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
/* Driver program to test above function*/
int main()
{
// Let us create below linked list.
// 85->15->18->20->85->35->4->20->NULL
struct Node* head = NULL;
push(&head, 20);
push(&head, 4);
push(&head, 35);
push(&head, 85);
push(&head, 20);
push(&head, 18);
push(&head, 15);
push(&head, 85);
cout << firstNonRepeating(head);
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
class GFG
{
// Java program to find first non-repeating
// element in a linked list
/* Link list node */
static class Node
{
public int data;
public Node next;
public Node(){
this.data = 0;
this.next = null;
}
public Node(int data,Node next){
this.data = data;
this.next = next;
}
};
/* Function to find the first non-repeating
element in the linked list */
static int firstNonRepeating(Node head)
{
// Create an empty map and insert all linked
// list elements into hash table
HashMap<Integer,Integer> mp = new HashMap<>();
for (Node temp=head; temp != null; temp = temp.next){
if(mp.containsKey(temp.data)){
mp.put(temp.data,mp.get(temp.data)+1);
}
else{
mp.put(temp.data,1);
}
}
// Traverse the linked list again and return
// the first node whose count is 1
for (Node temp=head; temp!=null; temp=temp.next){
if (mp.get(temp.data) == 1)
return temp.data;
}
return -1;
}
/* Function to push a node */
static Node push(Node head_ref, int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = head_ref;
head_ref = new_node;
return head_ref;
}
/* Driver program to test above function*/
public static void main(String args[])
{
// Let us create below linked list.
// 85->15->18->20->85->35->4->20->NULL
Node head = null;
head = push(head, 20);
head = push(head, 4);
head = push(head, 35);
head = push(head, 85);
head = push(head, 20);
head = push(head, 18);
head = push(head, 15);
head = push(head, 85);
System.out.print(firstNonRepeating(head));
}
}
// This code is contributed by shinjanpatra
Python3
# Python3 program to find first non-repeating
# element in a linked list
# Link list node
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Function to find the first non-repeating
# element in the linked list
def firstNonRepeating(head):
# Create an empty map and insert all linked
# list elements into hash table
mp = dict()
temp = head
while (temp != None):
if temp.data not in mp:
mp[temp.data] = 0
mp[temp.data] += 1
temp = temp.next
temp = head
# Traverse the linked list again and return
# the first node whose count is 1
while (temp != None):
if temp.data in mp:
if mp[temp.data] == 1:
return temp.data
temp = temp.next
return -1
# Function to push a node
def push(head_ref, new_data):
new_node = Node(new_data)
new_node.next = head_ref
head_ref = new_node
return head_ref
# Driver code
if __name__=='__main__':
# Let us create below linked list.
# 85->15->18->20->85->35->4->20->NULL
head = None
head = push(head, 20)
head = push(head, 4)
head = push(head, 35)
head = push(head, 85)
head = push(head, 20)
head = push(head, 18)
head = push(head, 15)
head = push(head, 85)
print(firstNonRepeating(head))
# This code is contributed by rutvik_56
C#
using System;
using System.Collections.Generic;
public class Gfg {
static void Main(string[] args)
{
// Let us create below linked list.
// 85->15->18->20->85->35->4->20->NULL
Node head = null;
push(ref head, 20);
push(ref head, 4);
push(ref head, 35);
push(ref head, 85);
push(ref head, 20);
push(ref head, 18);
push(ref head, 15);
push(ref head, 85);
Console.WriteLine(firstNonRepeating(head));
}
// Function to find the first non-repeating
// element in the linked list
static int firstNonRepeating(Node head)
{
// Create an empty map and insert all linked
// list elements into hash table
Dictionary<int, int> mp
= new Dictionary<int, int>();
for (Node temp = head; temp != null;
temp = temp.next)
if (mp.ContainsKey(temp.data))
mp[temp.data]++;
else
mp[temp.data] = 1;
// Traverse the linked list again and return
// the first node whose count is 1
for (Node temp = head; temp != null;
temp = temp.next)
if (mp[temp.data] == 1)
return temp.data;
return -1;
}
// Function to push a node
static void push(ref Node headRef, int newData)
{
Node newNode
= new Node{ data = newData, next = headRef };
headRef = newNode;
}
class Node {
public int data;
public Node next;
}
}
JavaScript
<script>
// Javascript program to find first non-repeating
// element in a linked list
/* Link list node */
class Node
{
constructor()
{
this.data = 0;
this.next = null;
}
};
/* Function to find the first non-repeating
element in the linked list */
function firstNonRepeating(head)
{
// Create an empty map and insert all linked
// list elements into hash table
var mp = new Map();
for (var temp=head; temp!=null; temp=temp.next)
{
if(mp.has(temp.data))
{
mp.set(temp.data , mp.get(temp.data)+1)
}
else
{
mp.set(temp.data, 1)
}
}
// Traverse the linked list again and return
// the first node whose count is 1
for (var temp=head; temp!=null; temp=temp.next)
if (mp.get(temp.data) == 1)
return temp.data;
return -1;
}
/* Function to push a node */
function push(head_ref, new_data)
{
var new_node = new Node();
new_node.data = new_data;
new_node.next = (head_ref);
(head_ref) = new_node;
return head_ref;
}
/* Driver program to test above function*/
// Let us create below linked list.
// 85.15.18.20.85.35.4.20.null
var head = null;
head = push(head, 20);
head = push(head, 4);
head = push(head, 35);
head = push(head, 85);
head = push(head, 20);
head = push(head, 18);
head = push(head, 15);
head = push(head, 85);
document.write( firstNonRepeating(head));
</script>
Time Complexity: O(N)
Auxiliary Space: O(N), for the map
Approach : Using two loops
In this approach, we use two loops to traverse the linked list. For each node in the linked list, we traverse the rest of the linked list to check if it is a non-repeating node. If we find a node that is not repeated in the linked list, we return that node.
Traverse the linked list starting from the head node.
For each node in the linked list, traverse the rest of the linked list to check if it is a non-repeating node.
To check if a node is non-repeating, compare its data value with the data value of all the nodes after it in the linked list. If there is another node with the same data value, then the current node is not a non-repeating node.
If a non-repeating node is found, return its data value.
If no non-repeating node is found, return -1 to indicate that no non-repeating node exists in the linked list.
Time Complexity:
C++
// C++ program to find first non-repeating
// element in a linked list
#include<bits/stdc++.h>
using namespace std;
/* Link list node */
struct Node
{
int data;
struct Node* next;
};
/* Function to find the first non-repeating
element in the linked list */
// Function to find the first non-repeating element in a linked list
int firstNonRepeatingNode(Node* head) {
Node* curr = head;
while (curr != NULL) {
bool isNonRepeating = true;
Node* temp = head;
while (temp != NULL) {
if (curr != temp && curr->data == temp->data) {
isNonRepeating = false;
break;
}
temp = temp->next;
}
if (isNonRepeating) {
return curr->data;
}
curr = curr->next;
}
return -1; // No non-repeating node found
}
/* Function to push a node */
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
/* Driver program to test above function*/
int main()
{
// Let us create below linked list.
// 85->15->18->20->85->35->4->20->NULL
struct Node* head = NULL;
push(&head, 20);
push(&head, 4);
push(&head, 35);
push(&head, 85);
push(&head, 20);
push(&head, 18);
push(&head, 15);
push(&head, 85);
cout << firstNonRepeatingNode(head);
return 0;
}
Java
// Java program to find the first non-repeating element in a linked list
import java.util.*;
// Link list node
class Node {
int data;
Node next;
// Constructor
public Node(int data) {
this.data = data;
this.next = null;
}
}
// Class to represent a linked list
class LinkedList {
// Function to find the first non-repeating element in a linked list
static int firstNonRepeatingNode(Node head) {
Node curr = head;
while (curr != null) {
boolean isNonRepeating = true;
Node temp = head;
while (temp != null) {
if (curr != temp && curr.data == temp.data) {
isNonRepeating = false;
break;
}
temp = temp.next;
}
if (isNonRepeating) {
return curr.data;
}
curr = curr.next;
}
return -1; // No non-repeating node found
}
// Function to push a node at the beginning of the linked list
static Node push(Node head_ref, int new_data) {
Node new_node = new Node(new_data);
new_node.next = head_ref;
head_ref = new_node;
return head_ref;
}
// Driver program to test above functions
public static void main(String[] args) {
// Let us create a linked list: 85->15->18->20->85->35->4->20->NULL
Node head = null;
head = push(head, 20);
head = push(head, 4);
head = push(head, 35);
head = push(head, 85);
head = push(head, 20);
head = push(head, 18);
head = push(head, 15);
head = push(head, 85);
// Find the first non-repeating element in the linked list
int result = firstNonRepeatingNode(head);
System.out.println(result);
}
}
// THIS CODE IS CONTRIBUTED BY CHANDAN AGARWAL
Python3
# Python program to find first non-repeating
# element in a linked list
# Link list node
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Function to find the first non-repeating element in a linked list
def firstNonRepeatingNode(head):
curr = head
while curr != None:
isNonRepeating = True
temp = head
while temp != None:
if curr != temp and curr.data == temp.data:
isNonRepeating = False
break
temp = temp.next
if isNonRepeating:
return curr.data
curr = curr.next
return -1 # No non-repeating node found
# Function to push a node
def push(head_ref, new_data):
new_node = Node(new_data)
new_node.next = head_ref
head_ref = new_node
return head_ref
# Driver program to test above function
if __name__ == '__main__':
# Let us create below linked list.
# 85->15->18->20->85->35->4->20->NULL
head = None
head = push(head, 20)
head = push(head, 4)
head = push(head, 35)
head = push(head, 85)
head = push(head, 20)
head = push(head, 18)
head = push(head, 15)
head = push(head, 85)
print(firstNonRepeatingNode(head))
JavaScript
// Define the 'Node' class
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
// Function to find the first non-repeating element in a linked list
function firstNonRepeatingNode(head) {
let curr = head;
while (curr !== null) {
let isNonRepeating = true;
let temp = head;
while (temp !== null) {
if (curr !== temp && curr.data === temp.data) {
isNonRepeating = false;
break;
}
temp = temp.next;
}
if (isNonRepeating) {
return curr.data;
}
curr = curr.next;
}
return -1; // No non-repeating node found
}
// Function to push a node
function push(head_ref, new_data) {
let new_node = new Node(new_data);
new_node.next = head_ref;
head_ref = new_node;
return head_ref;
}
// Driver program to test above functions
let head = null;
// Create the linked list
head = push(head, 20);
head = push(head, 4);
head = push(head, 35);
head = push(head, 85);
head = push(head, 20);
head = push(head, 18);
head = push(head, 15);
head = push(head, 85);
console.log(firstNonRepeatingNode(head));
// THIS CODE IS CONTRIBUTED BY CHANDAN AGARWAL
Output:
15
Time Complexity:
The time complexity of this approach is O(n^2), where n is the number of nodes in the linked list. This is because for each node in the linked list, we need to traverse the rest of the linked list to check if it is a non-repeating node. Therefore, the total number of comparisons required is n(n-1)/2, which is O(n^2).
Space Complexity:
The space complexity of this approach is O(1), as we are not using any extra data structures to store the nodes of the linked list or their frequency counts. We are only using a constant amount of memory to store the pointers and variables required to traverse the linked list and check for non-repeating nodes.
Further Optimisations:
The above solution requires two traversals of linked list. In case we have many repeating elements, we can save one traversal by storing positions also in hash table. Please refer last method of Given a string, find its first non-repeating character for details.
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