Finding Median in a Sorted Linked List
Last Updated :
07 Dec, 2023
Given A sorted linked list of N
elements. The task is to find the median in the given Sorted Linked List.
We know that median in a sorted array is the middle element.
Procedure to find median of N sorted numbers:
if N is odd:
median is N/2th element
else
median is N/2th element + (N/2+1)th element
Examples:
Input : 1->2->3->4->5->NULL
Output : 3
Input : 1->2->3->4->5->6->NULL
Output : 3.5
Simple approach
- Traverse the linked list and count all elements.
- if count is odd then again traverse the linked list and find n/2th element.
- if count is even then again traverse the linked list and find:
(n/2th element+ (n/2+1)th element)/2
Note: The above solution traverse the linked list two times.
Efficient Approach: an efficient approach is to traverse the list using two pointers to find the number of elements. See method 2 of this post.
We can use the above algorithm for finding the median of the linked list. Using this algorithm we won't need to count the number of element:
- if the fast_ptr is Not NULL then it means linked list contain odd element we simply print the data of the slow_ptr.
- else if fast_ptr reach to NULL its means linked list contain even element we create backup of the previous node of slow_ptr and print (previous node of slow_ptr+ slow_ptr->data)/2
Below is the implementation of the above approach:
C++
// C++ program to find median
// of a linked list
#include <bits/stdc++.h>
using namespace std;
// Link list node
struct Node {
int data;
struct Node* next;
};
/* Function to get the median of the linked list */
void printMidean(Node* head)
{
Node* slow_ptr = head;
Node* fast_ptr = head;
Node* pre_of_slow = head;
if (head != NULL) {
while (fast_ptr != NULL && fast_ptr->next != NULL) {
fast_ptr = fast_ptr->next->next;
// previous of slow_ptr
pre_of_slow = slow_ptr;
slow_ptr = slow_ptr->next;
}
// if the below condition is true linked list
// contain odd Node
// simply return middle element
if (fast_ptr != NULL)
cout << "Median is : " << slow_ptr->data;
// else linked list contain even element
else
cout << "Median is : "
<< float(slow_ptr->data + pre_of_slow->data) / 2;
}
}
/* Given a reference (pointer to
pointer) to the head of a list
and an int, push a new node on
the front of the list. */
void push(struct Node** head_ref, int new_data)
{
// allocate node
Node* new_node = new Node;
// put in the data
new_node->data = new_data;
// link the old list
// off the new node
new_node->next = (*head_ref);
// move the head to point
// to the new node
(*head_ref) = new_node;
}
// Driver Code
int main()
{
// Start with the
// empty list
struct Node* head = NULL;
// Use push() to construct
// below list
// 1->2->3->4->5->6
push(&head, 6);
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
// Check the count
// function
printMidean(head);
return 0;
}
Java
// Java program to find median
// of a linked list
class GFG
{
// Link list node
static class Node
{
int data;
Node next;
};
/* Function to get the median of the linked list */
static void printMidean(Node head)
{
Node slow_ptr = head;
Node fast_ptr = head;
Node pre_of_slow = head;
if (head != null)
{
while (fast_ptr != null && fast_ptr.next != null)
{
fast_ptr = fast_ptr.next.next;
// previous of slow_ptr
pre_of_slow = slow_ptr;
slow_ptr = slow_ptr.next;
}
// if the below condition is true linked list
// contain odd Node
// simply return middle element
if (fast_ptr != null)
{
System.out.print("Median is : " + slow_ptr.data);
}
// else linked list contain even element
else
{
System.out.print("Median is : "
+ (float) (slow_ptr.data + pre_of_slow.data) / 2);
}
}
}
/* Given a reference (pointer to
pointer) to the head of a list
and an int, push a new node on
the front of the list. */
static Node push(Node head_ref, int new_data)
{
// allocate node
Node new_node = new Node();
// put in the data
new_node.data = new_data;
// link the old list
// off the new node
new_node.next = head_ref;
// move the head to point
// to the new node
head_ref = new_node;
return head_ref;
}
// Driver Code
public static void main(String[] args)
{
// Start with the
// empty list
Node head = null;
// Use push() to construct
// below list
// 1.2.3.4.5.6
head = push(head, 6);
head = push(head, 5);
head = push(head, 4);
head = push(head, 3);
head = push(head, 2);
head = push(head, 1);
// Check the count
// function
printMidean(head);
}
}
// This code is contributed by PrinciRaj1992
Python3
# Python3 program to find median
# of a linked list
class Node:
def __init__(self, value):
self.data = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# Create Node and make linked list
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# Function to get the median
# of the linked list
def printMedian(self):
slow_ptr = self.head
fast_ptr = self.head
pre_of_show = self.head
count = 0
while (fast_ptr != None and
fast_ptr.next != None):
fast_ptr = fast_ptr.next.next
# Previous of slow_ptr
pre_of_slow = slow_ptr
slow_ptr = slow_ptr.next
# If the below condition is true
# linked list contain odd Node
# simply return middle element
if (fast_ptr):
print("Median is :", (slow_ptr.data))
# Else linked list contain even element
else:
print("Median is :", (slow_ptr.data +
pre_of_slow.data) / 2)
# Driver code
llist = LinkedList()
# Use push() to construct
# below list
# 1->2->3->4->5->6
llist.push(6)
llist.push(5)
llist.push(4)
llist.push(3)
llist.push(2)
llist.push(1)
# Check the count
# function
llist.printMedian()
# This code is contributed by grand_master
C#
// C# program to find median
// of a linked list
using System;
class GFG
{
// Link list node
class Node
{
public int data;
public Node next;
};
/* Function to get the median
of the linked list */
static void printMidean(Node head)
{
Node slow_ptr = head;
Node fast_ptr = head;
Node pre_of_slow = head;
if (head != null)
{
while (fast_ptr != null &&
fast_ptr.next != null)
{
fast_ptr = fast_ptr.next.next;
// previous of slow_ptr
pre_of_slow = slow_ptr;
slow_ptr = slow_ptr.next;
}
// if the below condition is true linked list
// contain odd Node
// simply return middle element
if (fast_ptr != null)
{
Console.Write("Median is : " +
slow_ptr.data);
}
// else linked list contain even element
else
{
Console.Write("Median is : " +
(float)(slow_ptr.data +
pre_of_slow.data) / 2);
}
}
}
/* Given a reference (pointer to
pointer) to the head of a list
and an int, push a new node on
the front of the list. */
static Node push(Node head_ref, int new_data)
{
// allocate node
Node new_node = new Node();
// put in the data
new_node.data = new_data;
// link the old list
// off the new node
new_node.next = head_ref;
// move the head to point
// to the new node
head_ref = new_node;
return head_ref;
}
// Driver Code
public static void Main(String[] args)
{
// Start with the
// empty list
Node head = null;
// Use push() to construct
// below list
// 1->2->3->4->5->6
head = push(head, 6);
head = push(head, 5);
head = push(head, 4);
head = push(head, 3);
head = push(head, 2);
head = push(head, 1);
// Check the count
// function
printMidean(head);
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// Javascript program to find median
// of a linked list
// A linked list node
class Node {
constructor() {
this.data = 0;
this.next = null;
}
}
/* Function to get the median of the linked list */
function printMidean( head)
{
var slow_ptr = head;
var fast_ptr = head;
var pre_of_slow = head;
if (head != null)
{
while (fast_ptr != null && fast_ptr.next != null)
{
fast_ptr = fast_ptr.next.next;
// previous of slow_ptr
pre_of_slow = slow_ptr;
slow_ptr = slow_ptr.next;
}
// if the below condition is true linked list
// contain odd Node
// simply return middle element
if (fast_ptr != null)
{
document.write("Median is : " + slow_ptr.data);
}
// else linked list contain even element
else
{
document.write("Median is : "
+ (slow_ptr.data + pre_of_slow.data) / 2);
}
}
}
/* Given a reference (pointer to
pointer) to the head of a list
and an int, push a new node on
the front of the list. */
function push( head_ref, new_data)
{
// allocate node
var new_node = new Node();
// put in the data
new_node.data = new_data;
// link the old list
// off the new node
new_node.next = head_ref;
// move the head to point
// to the new node
head_ref = new_node;
return head_ref;
}
// Driver Code
// Start with the
// empty list
var head = null;
// Use push() to construct
// below list
// 1.2.3.4.5.6
head = push(head, 6);
head = push(head, 5);
head = push(head, 4);
head = push(head, 3);
head = push(head, 2);
head = push(head, 1);
// Check the count
// function
printMidean(head);
// This code is contributed by jana_sayantan.
</script>
Using Binary Search: The idea is simple we have to find the middle element of a linked list .
As linked list is sorted then we can easily find middle element with the help of binary search
- This approach involves dividing the linked list into two halves
- comparing the middle element with the median and making a recursive call on the appropriate half.
C++
#include <iostream>
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
double findMedian(ListNode *head) {
int n = 0;
ListNode *p = head;
// Count the number of elements in the linked list
while (p) {
n++;
p = p->next;
}
// Call the helper function to find the median
return (n & 1) ? findKth(head, n / 2 ) :
(findKth(head, n / 2) + findKth(head, n / 2 )) / 2.0;
}
private:
int findKth(ListNode *head, int k) {
ListNode *p = head;
// Iterate through the linked list until the kth element
while (k-- > 0) {
p = p->next;
}
// Return the kth element
return p->val;
}
};
int main() {
ListNode *head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(4);
head->next->next->next->next = new ListNode(5);
Solution solution;
std::cout << "The median is:-> "<<solution.findMedian(head) << std::endl;
return 0;
}
//This code is contributed by Veerendra Singh Rajpoot
Java
class ListNode {
int val;
ListNode next;
ListNode(int x)
{
val = x;
next = null;
}
}
class Solution {
public double findMedian(ListNode head)
{
int n = 0;
ListNode p = head;
// Count the number of elements in the linked list
while (p != null) {
n++;
p = p.next;
}
// Call the helper function to find the median
return (n % 2 == 1) ? findKth(head, n / 2)
: (findKth(head, n / 2)
+ findKth(head, n / 2 - 1))
/ 2.0;
}
private int findKth(ListNode head, int k)
{
ListNode p = head;
// Iterate through the linked list until the kth
// element
while (k > 0) {
p = p.next;
k--;
}
// Return the kth element
return p.val;
}
}
public class GFG {
public static void main(String[] args)
{
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
Solution solution = new Solution();
System.out.println("The median is: "
+ solution.findMedian(head));
}
}
Python
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class GFG:
def findMedian(self, head):
n = 0
p = head
# Count the number of elements in linked list
while p:
n += 1
p = p.next
# Call the helper function to the find the median
return self.find_kth(head, n // 2) if n % 2 == 1 else (self.find_kth(head, n // 2) + self.find_kth(head, n // 2 - 1)) / 2.0
def find_kth(self, head, k):
p = head
# Iterate through the linked list until
# kth element
while k > 0:
p = p.next
k -= 1
return p.val
# Main driver code
if __name__ == "__main__":
# Creating a linked list: 1 -> 2 -> 3 -> 4 -> 5
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)
# Creating an instance of Solution class
solution = GFG()
# Finding and printing the median of linked list
print "The median is:", solution.findMedian(head)
C#
using System;
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int x)
{
val = x;
next = null;
}
}
public class Solution
{
public double FindMedian(ListNode head)
{
int n = 0;
ListNode p = head;
// Count the number of elements in the linked list
while (p != null)
{
n++;
p = p.next;
}
// Call the helper function to find the median
return (n % 2 == 1) ? FindKth(head, n / 2)
: (FindKth(head, n / 2)
+ FindKth(head, n / 2 - 1))
/ 2.0;
}
private int FindKth(ListNode head, int k)
{
ListNode p = head;
// Iterate through the linked list until the kth
// element
while (k > 0)
{
p = p.next;
k--;
}
// Return the kth element
return p.val;
}
}
public class GFG
{
public static void Main(string[] args)
{
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
Solution solution = new Solution();
Console.WriteLine("The median is:-> "
+ solution.FindMedian(head));
}
}
JavaScript
class ListNode {
constructor(val) {
this.val = val;
this.next = null;
}
}
class Solution {
findMedian(head) {
let n = 0;
let p = head;
// Count the number of elements in the linked list
while (p) {
n++;
p = p.next;
}
// Call the helper function to find the median
return (n % 2 === 1) ? this.findKth(head, Math.floor(n / 2)) :
(this.findKth(head, n / 2) + this.findKth(head, n / 2 - 1)) / 2.0;
}
findKth(head, k) {
let p = head;
// Iterate through the linked list until the kth element
while (k > 0) {
p = p.next;
k--;
}
// Return the kth element's value
return p.val;
}
}
const head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
const solution = new Solution();
console.log("The median is: " + solution.findMedian(head));
Explanation:
In this code, the findMedian function first counts the number of elements in the linked list using a while loop. After that, it calls the findKth function to find the kth element in the linked list, which can be used to find the median. If the number of elements is odd, the median is the middle element, and if it is even, the median is the average of the two middle elements. The findKth function uses another while loop to iterate through the linked list until the kth element, and returns the value of that element.
Time Complexity O(n): The time complexity of this approach is O(n), where n is the number of elements in the linked list. This is because in the worst case, the linked list needs to be traversed twice - once to count the number of elements and once to find the median. The first while loop in the findMedian function takes O(n) time, and the second while loop in the findKth function takes O(k) time, where k is the index of the median. In the worst case, k can be n/2, so the overall time complexity is O(n).
Auxiliary Space: O(1):The space complexity of this approach is O(1), because only a few variables are used, and no extra data structures are needed. The linked list is traversed in place, so no additional memory is used to store the elements.
This approach is contributed by Veerendra Singh Rajpoot
If you find anything wrong or incorrect please let us know.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In 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
4 min read
Sorting Algorithms A 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