DEV Community

Cover image for Day 91 of 100 days dsa coding challenge
Manasi Patil
Manasi Patil

Posted on

Day 91 of 100 days dsa coding challenge

Taking on a new challenge: solving GeeksforGeeks POTD daily and sharing my solutions! πŸ’»πŸ”₯
The goal: sharpen problem-solving skills, level up coding, and learn something new every day. Follow my journey! πŸš€

100DaysOfCode #CodingChallenge #ProblemSolving #GeeksforGeeks #DeveloperJourney

Problem:

https://www.geeksforgeeks.org/problems/flattening-a-linked-list/1

Flattening a Linked List

Difficulty: Medium Accuracy: 51.53%

Given a linked list containing n head nodes where every node in the linked list contains two pointers:
(i) next points to the next node in the list.
(ii) bottom points to a sub-linked list where the current node is the head.
Each of the sub-linked lists nodes and the head nodes are sorted in ascending order based on their data. Flatten the linked list such that all the nodes appear in a single level while maintaining the sorted order.
Note:

  1. ↓ represents the bottom pointer and β†’ represents the next pointer.
  2. The flattened list will be printed using the bottom pointer instead of the next pointer.

Examples:
Input:


Output: 5 -> 7 -> 8 -> 10 -> 19 -> 20 -> 22 -> 28 -> 40 -> 45.
Explanation:
Bottom pointer of 5 is pointing to 7.
Bottom pointer of 7 is pointing to 8.
Bottom pointer of 10 is pointing to 20 and so on.
So, after flattening the linked list the sorted list will be
5 -> 7 -> 8 -> 10 -> 19 -> 20 -> 22 -> 28 -> 40 -> 45.
Input:


Output: 5 -> 7 -> 8 -> 10 -> 19 -> 22 -> 28 -> 30 -> 50
Explanation:
Bottom pointer of 5 is pointing to 7.
Bottom pointer of 7 is pointing to 8.
Bottom pointer of 8 is pointing to 30 and so on.
So, after flattening the linked list the sorted list will be
5 -> 7 -> 8 -> 10 -> 19 -> 22 -> 28 -> 30 -> 50.
Constraints:
0 ≀ n ≀ 100
1 ≀ number of nodes in sub-linked list(mi) ≀ 50
1 ≀ node->data ≀ 104

Solution:
class Solution:
def merge(self, a, b):
if not a:
return b
if not b:
return a
if a.data < b.data:
result = a
result.bottom = self.merge(a.bottom, b)
else:
result = b
result.bottom = self.merge(a, b.bottom)
result.next = None
return result

def flatten(self, root):
    if not root or not root.next:
        return root
    root.next = self.flatten(root.next)
    root = self.merge(root, root.next)
    return root
Enter fullscreen mode Exit fullscreen mode

Top comments (0)