Solved Partition List challenge with two-list approach in #100DaysOfCode

Day 72: Partition List 🔗 I'm back to linked lists on Day 72 of #100DaysOfCode by solving "Partition List." The challenge is to rearrange a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x, while preserving the original relative order within each partition. My solution uses a two-list approach with dummy nodes: Creation of Two Lists: I initialize two separate dummy nodes: less_dummy and greater_dummy. Partitioning: I iterate through the original list once. If a node's value is less than x, I append it to the less list; otherwise, I append it to the greater list. This inherently preserves the relative order within each group. Merging: After the single pass, I set the next pointer of the tail of the less list to the head of the greater list (less_tail.next = greater_dummy.next). Crucially, I set the tail of the greater list to None to prevent cycles (greater_tail.next = None). This single-pass method achieves an optimal O(n) time complexity and O(1) extra space complexity (excluding the new nodes being rearranged). My solution was accepted with 100% runtime efficiency! #Python #DSA #Algorithms #LinkedList #100DaysOfCode #ProblemSolving

  • graphical user interface

To view or add a comment, sign in

Explore content categories