Partition Linked List by Value x

🚀 Day 33 / 100 | Partition List -Intuition: This problem is based on Linked List partitioning. We are given the head of a linked list and a value x. Goal is to rearrange the list such that all nodes with values less than x come before nodes with values greater than or equal to x. we must preserve the original relative order of nodes in each partition. "So instead of modifying values, we create two separate lists and then connect them". -Approach: O(n) Initialize two dummy nodes: l1 and l2. These will store nodes less than x and nodes greater than or equal to x respectively. Traverse the original linked list from head to null. If current node value < x, attach it to the small list. Otherwise, attach it to the greater list. Move the pointers accordingly. After traversal, connect the end of the small list to the start of the greater list. Make sure to set greater.next = null to avoid cycle. Return l1.next as the new head. -Complexity: Time Complexity: O(n) Space Complexity: O(1) #100DaysOfCode #Java #DSA #LeetCode #LinkedList

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories