Posts

Showing posts with the label linked-list

Sorting a Linked List of 0's, 1's and 2's

Image
Problem Statement:- Given a linked list of N nodes where nodes can contain values 0s, 1s, and 2s only. The task is to segregate 0s, 1s, and 2s linked list such that all zeros segregate to the head side, 2s at the end of the linked list, and 1s in the mid of 0s and 2s. Example 1: I nput: N = 8 value[] = {1,2,2,1,2,0,2,2} Output: 0 1 1 2 2 2 2 2 Explanation: All the 0s are segregated to the left end of the linked list, 2s to the right end of the list, and 1s in between. Link to Problem:  Sorting a Linked List of 0's, 1's and 2's Solution:- The basic approach to solve this problem would be to store the count of  0's, 1's, and 2's and then changing the value of the nodes of the LinkedList.  And this is an optimal approach as well, many people will argue that since we are storing the count of  0's, 1's, and 2's, it will be using O(N) extra space. But no, we will be using O(1) space to store the count of elements, since, for each test case, we will only r...