Finding Median in a Sorted Linked List
Last Updated :
07 Dec, 2023
Given A sorted linked list of [Tex]N
[/Tex]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++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
};
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;
pre_of_slow = slow_ptr;
slow_ptr = slow_ptr->next;
}
if (fast_ptr != NULL)
cout << "Median is : " << slow_ptr->data;
else
cout << "Median is : "
<< float (slow_ptr->data + pre_of_slow->data) / 2;
}
}
void push( struct 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;
}
int main()
{
struct Node* head = NULL;
push(&head, 6);
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
printMidean(head);
return 0;
}
|
Java
class GFG
{
static class Node
{
int data;
Node next;
};
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;
pre_of_slow = slow_ptr;
slow_ptr = slow_ptr.next;
}
if (fast_ptr != null )
{
System.out.print( "Median is : " + slow_ptr.data);
}
else
{
System.out.print( "Median is : "
+ ( float ) (slow_ptr.data + pre_of_slow.data) / 2 );
}
}
}
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;
}
public static void main(String[] args)
{
Node head = null ;
head = push(head, 6 );
head = push(head, 5 );
head = push(head, 4 );
head = push(head, 3 );
head = push(head, 2 );
head = push(head, 1 );
printMidean(head);
}
}
|
Python3
class Node:
def __init__( self , value):
self .data = value
self . next = None
class LinkedList:
def __init__( self ):
self .head = None
def push( self , new_data):
new_node = Node(new_data)
new_node. next = self .head
self .head = new_node
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
pre_of_slow = slow_ptr
slow_ptr = slow_ptr. next
if (fast_ptr):
print ( "Median is :" , (slow_ptr.data))
else :
print ( "Median is :" , (slow_ptr.data +
pre_of_slow.data) / 2 )
llist = LinkedList()
llist.push( 6 )
llist.push( 5 )
llist.push( 4 )
llist.push( 3 )
llist.push( 2 )
llist.push( 1 )
llist.printMedian()
|
C#
using System;
class GFG
{
class Node
{
public int data;
public Node next;
};
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;
pre_of_slow = slow_ptr;
slow_ptr = slow_ptr.next;
}
if (fast_ptr != null )
{
Console.Write( "Median is : " +
slow_ptr.data);
}
else
{
Console.Write( "Median is : " +
( float )(slow_ptr.data +
pre_of_slow.data) / 2);
}
}
}
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;
}
public static void Main(String[] args)
{
Node head = null ;
head = push(head, 6);
head = push(head, 5);
head = push(head, 4);
head = push(head, 3);
head = push(head, 2);
head = push(head, 1);
printMidean(head);
}
}
|
Javascript
<script>
class Node {
constructor() {
this .data = 0;
this .next = null ;
}
}
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;
pre_of_slow = slow_ptr;
slow_ptr = slow_ptr.next;
}
if (fast_ptr != null )
{
document.write( "Median is : " + slow_ptr.data);
}
else
{
document.write( "Median is : "
+ (slow_ptr.data + pre_of_slow.data) / 2);
}
}
}
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;
}
var head = null ;
head = push(head, 6);
head = push(head, 5);
head = push(head, 4);
head = push(head, 3);
head = push(head, 2);
head = push(head, 1);
printMidean(head);
</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>
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;
while (p) {
n++;
p = p->next;
}
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;
while (k-- > 0) {
p = p->next;
}
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;
}
|
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;
while (p != null ) {
n++;
p = p.next;
}
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;
while (k > 0 ) {
p = p.next;
k--;
}
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
while p:
n + = 1
p = p. next
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
while k > 0 :
p = p. next
k - = 1
return p.val
if __name__ = = "__main__" :
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 )
solution = GFG()
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;
while (p != null )
{
n++;
p = p.next;
}
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;
while (k > 0)
{
p = p.next;
k--;
}
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;
while (p) {
n++;
p = p.next;
}
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;
while (k > 0) {
p = p.next;
k--;
}
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
Find extra node in the second Linked list
Given two Linked list L1 and L2. The second list L2 contains all the nodes of L1 along with 1 extra node. The task is to find that extra node. Examples: Input: L1 = 17 -> 7 -> 6 -> 16 L2 = 17 -> 7 -> 6 -> 16 -> 15 Output: 15 Explanation: Element 15 is not present in the L1 listI
7 min read
Count rotations in sorted and rotated linked list
Given a linked list of n nodes which is first sorted, then rotated by k elements. Find the value of k. The idea is to traverse singly linked list to check condition whether current node value is greater than value of next node. If the given condition is true, then break the loop. Otherwise increase
8 min read
Sort a Linked List in wave form
Given an unsorted Linked List of integers. The task is to sort the Linked List into a wave like Line. A Linked List is said to be sorted in Wave Form if the list after sorting is in the form: list[0] >= list[1] <= list[2] >= â¦.. Where list[i] denotes the data at i-th node of the Linked List
11 min read
Write a function to get Nth node in a Linked List
Given a LinkedList and an index (1-based). The task is to find the data value stored in the node at that kth position. If no such node exists whose index is k then return -1. Example:Â Input: 1->10->30->14, index = 2Output: 10Explanation: The node value at index 2 is 10 Input: 1->32->
11 min read
Find Middle of the Linked List
Given a singly linked list, the task is to find the middle of the linked list. If the number of nodes are even, then there would be two middle nodes, so return the second middle node. Example: Input: linked list: 1->2->3->4->5Output: 3 Explanation: There are 5 nodes in the linked list an
14 min read
Find the balanced node in a Linked List
Given a linked list, the task is to find the balanced node in a linked list. A balanced node is a node where the sum of all the nodes on its left is equal to the sum of all the node on its right, if no such node is found then print -1. Examples: Input: 1 -> 2 -> 7 -> 10 -> 1 -> 6 -
8 min read
Remove duplicates from a sorted linked list
Given a linked list sorted in non-decreasing order. Return the list by deleting the duplicate nodes from the list. The returned list should also be in non-decreasing order. Example: Input : Linked List = 11->11->11->21->43->43->60Output : 11->21->43->60Explanation: Input :
15+ min read
Find a peak element in Linked List
Given a linked list of integers, the task is to find a peak element in the given linked list. An element is a peak, if it is greater than or equals to its neighbors. For boundary elements, consider only one neighbor. Examples: Input : List = {1 -> 6 -> 8 -> 4 -> 12} Output : 8Explanation
8 min read
Insertion Sort for Singly Linked List
Given a singly linked list, the task is to sort the list (in ascending order) using the insertion sort algorithm. Examples: Input: 5->4->1->3->2Output: 1->2->3->4->5Input: 4->3->2->1Output: 1->2->3->4 The prerequisite is Insertion Sort on Array. The idea is
8 min read
Check if a linked list is sorted in non-increasing order
Given a Linked List, The task is to check whether the Linked List is sorted in a non-increasing order. Examples : Input : 8 -> 7 -> 5 -> 2 -> 1Output: YesInput : 24 -> 12 -> 9 -> 11 -> 8 -> 2Output: No [Expected Approach - 1] Using Recursion - O(n) Time and O(n) Space:The
12 min read