sorting:

Insertion Sort List

Algorithm of Insertion Sort Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. It repeats until no input elements remain. Example 1 Input: 4->2->1->3 Output: 1->2->3->4 Example 2 Input: -1->5->3->4->0 Output: -1->0->3->4->5 Solution # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.

by lek tin in "algorithm" access_time 1-min read

Sort List

Sort a linked list in O(n log n) time using constant space complexity. Example 1 Input: 4->2->1->3 Output: 1->2->3->4 Example 2 Input: -1->5->3->4->0 Output: -1->0->3->4->5 Solution (merge sort - top down) Time: O(NlogN) Space: O(logN) Doesn’t satisfy the requirement # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def sortList(self, head: ListNode) -> ListNode: if not head or not head.

by lek tin in "algorithm" access_time 2-min read