leetcode new problems

This commit is contained in:
2026-02-11 14:48:41 +05:30
parent 192ce44a81
commit 0f52d46c67
29 changed files with 658 additions and 5 deletions
+34
View File
@@ -0,0 +1,34 @@
class Solution{
public :
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2){
if(!l1 || !l2) return l1?l1:l2;
if(l1->val < l2->val){
l1->next = mergeTwoLists(l1->next, l2);
return l1;
}else{
l2->next = mergeTwoLists(l1,l2->next);
return l2;
}
}
ListNode* mergeKLists(vector<ListNode*> &lists){
if(lists.empty()) return nullptr;
return divideAndConquer(lists, 0 , lists.size()-1);
}
ListNode* divideAndConquer(vector<ListNode*> &lists, int left, int right){
if(left == right) return lists[left];
int mid = left + (right-left)/2;
ListNode* l1 = divideAndConquer(lists, left, mid);
ListNode* l2 = divideAndConquer(lists, mid+1, right);
return mergeTwoLists(l1,l2);
}
};
//We recursively split the K lists into smaller groups, merge pairs of lists at the bottom, and keep merging upward until one sorted list remains.
//TC: O(nlogk) , Each level merges all nodes once, Number of levels = log₂(k), naive merging takes O(nk)
//SC : O(logK)