AfterAcademy Tech
•
04 Dec 2019

Difficulty: Medium
Asked in: Microsoft, Google
Problem Description: Sort a linked list using insertion sort and return its head.
Example 1
Input: 8->0->1->3
Output: 0->1->3->8
Example 2
Input: -1->7->3->4->2
Output: -1->2->3->4->7
Possible follow-up questions to ask the interviewer :
The node structure for the Linked List passed to your function will be
class Node
{
int val
Node next
Node(int v)
{
val = v
next = NULL
}
}
Let us first understand the flow of insertion sort. At any point of time in insertion sort, it divide the array into three parts
Everything before the current element is sorted part and everything after the current element is unsorted part.At each iteration we will pick the first element from the unsorted part, we will find the position of that element within the sorted list, and insert it there. It repeats until no element is present in the unsorted part.
To insert, we will use a helper function sortedInsert() which will return the head of the sorted list after insertion. sortedInsert() accepts a list head and a node as an argument and iterates through the list until it finds an element greater than the node.
Solution Steps
4. Return sorted_head
Pseudo Code
Node insertionSortLinkedList(Node head)
{
Node curr = head
Node sorted_head = NULL
while (curr != NULL)
{
Node currNext = curr.next
sorted_head = sortedInsert(sorted_head,curr)
curr = currNext
}
return sorted_head
}
Node sortedInsert(Node sorted_head, Node new_node)
{
// Insertion at first position
if(sorted_head == NULL or head.data >= new_node.data)
{
new_node.next = sorted_head
return new_node
}
else
{
Node curr = sorted_head
while(curr.next != NULL and
curr.next.data < new_node.data)
curr = curr.next
new_node.next = curr.next
curr.next = new_node
}
return sorted_head
}
Complexity Analysis
In the worst case, we could have to traverse the whole partially sorted list to insert a node in the correct position.(Think!)
Time Complexity: (Traversing the list) * (Inserting in Sorted List)
= O(n)*O(n) = O(n²)
Space Complexity = O(1)
Critical ideas to think!
May the code be with You!
Enjoy Algorithms!
AfterAcademy Tech
This is an interview problem asked by companies like Myntra, Visa, Oracle, Adobe, etc. The problem is to remove the duplicate nodes from the given Linked List so that only unique nodes(with unique data values) are present.

AfterAcademy Tech
Given a Linked List, your task is to find whether the given singly linked list is a palindrome or not. This is an interview problem asked in many companies like Amazon, Microsoft, Adobe, Flipkart and other big companies.

AfterAcademy Tech
Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.

AfterAcademy Tech
Sort a linked list using Merge Sort. This is a very famous interview problem that demonstrates the concept of recursion. This problem is quite similar to Merge Sort in Arrays.
