Skip to content

Commit c450aea

Browse files
Add files via upload
1 parent 26fe9fa commit c450aea

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

Day148Question148/Documentati.pdf

129 KB
Binary file not shown.

Day148Question148/Question.pdf

60.1 KB
Binary file not shown.

Day148Question148/Solution.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution:
2+
def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
3+
# Base Case: If the list has 0 or 1 elements, it's already sorted
4+
if not head or not head.next:
5+
return head
6+
7+
# Find the midpoint of the list using slow and fast pointers
8+
slow, fast = head, head.next
9+
while fast and fast.next:
10+
slow = slow.next
11+
fast = fast.next.next
12+
13+
# Split the list into two halves
14+
mid = slow.next
15+
slow.next = None
16+
17+
# Recursively sort both halves
18+
left = self.sortList(head)
19+
right = self.sortList(mid)
20+
21+
# Merge the two sorted halves
22+
dummy = ListNode(0)
23+
curr = dummy
24+
while left and right:
25+
if left.val < right.val:
26+
curr.next = left
27+
left = left.next
28+
else:
29+
curr.next = right
30+
right = right.next
31+
curr = curr.next
32+
33+
# Append any remaining nodes from either half
34+
curr.next = left or right
35+
36+
return dummy.next

0 commit comments

Comments
 (0)