title
stringlengths
3
77
title_slug
stringlengths
3
77
question_content
stringlengths
38
1.55k
tag
stringclasses
707 values
level
stringclasses
3 values
question_hints
stringlengths
19
3.98k
view_count
int64
8
630k
vote_count
int64
5
10.4k
content
stringlengths
0
43.9k
__index_level_0__
int64
0
109k
Valid Parentheses
valid-parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if:
String,Stack
Easy
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g. { { } [ ] [ [ [ ] ] ] } is VALID expression [ [ [ ] ] ] is VALID sub-expression { } [ ] is VALID sub-expression Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g. { { ( { } ) } } |_| { { ( ) } } |______| { { } } |__________| { } |________________| VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
1,192
11
```\nclass Solution {\npublic:\n bool isValid(string s) {\n stack<char> bracketStack;\n \n for(int i=0;i<s.size();i++){\n char openingBracket = s[i];\n //pushing all the opening brackets in stack\n if(openingBracket == \'(\' || openingBracket == \'{\' || openingBracket == \'[\'){\n bracketStack.push(s[i]);\n }\n else{\n //as soon as the bracket isn\'t opening check if the stack is empty or not\n if(!bracketStack.empty()){\n char top = bracketStack.top();\n //checking if the bracket is balanced or not\n if(top==\'(\' && s[i]==\')\' || top==\'{\' && s[i]==\'}\' || top==\'[\' && s[i]==\']\'){\n bracketStack.pop();\n }\n //if not balanced return false\n else\n return false;\n }\n //else if the stack is not empty return false\n else\n return false;\n }\n }\n \n if(bracketStack.empty()) \n return true;\n //if after traversal of the entire string there is still a bracket left in the stack that means brackets are unbalanced\n return false;\n }\n};\n//please upvote if you find it useful\n```
1,987
Valid Parentheses
valid-parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if:
String,Stack
Easy
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g. { { } [ ] [ [ [ ] ] ] } is VALID expression [ [ [ ] ] ] is VALID sub-expression { } [ ] is VALID sub-expression Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g. { { ( { } ) } } |_| { { ( ) } } |______| { { } } |__________| { } |________________| VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
2,870
7
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe use a stack to maintain the order of open brackets encountered.\nWhen a closing bracket is encountered, we check if it matches the last encountered open bracket.\nIf the brackets are balanced and correctly ordered, the stack should be empty at the end.\n\n---\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach used here is to iterate through the input string s character by character. We maintain a stack to keep track of open brackets encountered. When we encounter an open bracket (\'(\', \'{\', or \'[\'), we push it onto the stack. When we encounter a closing bracket (\')\', \'}\', or \']\'), we check if there is a matching open bracket at the top of the stack. If not, it means the brackets are not balanced, and we return false. If there is a matching open bracket, we pop it from the stack.\n\nAt the end of the loop, if the stack is empty, it indicates that all open brackets have been closed properly, and we return true. Otherwise, if there are unmatched open brackets left in the stack, we return false.\n\n---\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this solution is O(n), where n is the length of the input string s. This is because we iterate through the string once, and each character operation takes constant time.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(n) as well, where n is the length of the input string s. In the worst case, all characters in the string could be open brackets, and they would be pushed onto the stack.\n\n---\n\n\n# \uD83D\uDCA1"If you have come this far, I would like to kindly request your support by upvoting this solution, thus enabling it to reach a broader audience."\u2763\uFE0F\uD83D\uDCA1\n\n---\n\n\n# Code\n\n```C++ []\n#include <stack>\n#include <string>\n\nclass Solution {\npublic:\n bool isValid(string s) {\n stack<char> brackets;\n \n for (char c : s) {\n if (c == \'(\' || c == \'{\' || c == \'[\') {\n brackets.push(c);\n } else {\n if (brackets.empty()) {\n return false; // There\'s no matching open bracket.\n }\n \n char openBracket = brackets.top();\n brackets.pop();\n \n if ((c == \')\' && openBracket != \'(\') ||\n (c == \'}\' && openBracket != \'{\') ||\n (c == \']\' && openBracket != \'[\')) {\n return false; // Mismatched closing bracket.\n }\n }\n }\n \n return brackets.empty(); // All open brackets should be closed.\n }\n};\n```\n```Java []\nimport java.util.Stack;\n\nclass Solution {\n public boolean isValid(String s) {\n Stack<Character> brackets = new Stack<>();\n \n for (char c : s.toCharArray()) {\n if (c == \'(\' || c == \'{\' || c == \'[\') {\n brackets.push(c);\n } else {\n if (brackets.isEmpty()) {\n return false; // There\'s no matching open bracket.\n }\n \n char openBracket = brackets.pop();\n \n if ((c == \')\' && openBracket != \'(\') ||\n (c == \'}\' && openBracket != \'{\') ||\n (c == \']\' && openBracket != \'[\')) {\n return false; // Mismatched closing bracket.\n }\n }\n }\n \n return brackets.isEmpty(); // All open brackets should be closed.\n }\n}\n\n```\n```Python []\nclass Solution:\n def isValid(self, s: str) -> bool:\n brackets = []\n \n for c in s:\n if c in \'({[\':\n brackets.append(c)\n else:\n if not brackets:\n return False # There\'s no matching open bracket.\n \n open_bracket = brackets.pop()\n \n if (c == \')\' and open_bracket != \'(\') or (c == \'}\' and open_bracket != \'{\') or (c == \']\' and open_bracket != \'[\'):\n return False # Mismatched closing bracket.\n \n return not brackets # All open brackets should be closed.\n\n```\n```Javascript []\nvar isValid = function(s) {\n const brackets = [];\n \n for (let c of s) {\n if (c === \'(\' || c === \'{\' || c === \'[\') {\n brackets.push(c);\n } else {\n if (brackets.length === 0) {\n return false; // There\'s no matching open bracket.\n }\n \n const openBracket = brackets.pop();\n \n if ((c === \')\' && openBracket !== \'(\') || (c === \'}\' && openBracket !== \'{\') || (c === \']\' && openBracket !== \'[\')) {\n return false; // Mismatched closing bracket.\n }\n }\n }\n \n return brackets.length === 0; // All open brackets should be closed.\n};\n\n```\n```Ruby []\ndef is_valid(s)\n brackets = []\n \n s.chars.each do |c|\n if c == \'(\' || c == \'{\' || c == \'[\'\n brackets.push(c)\n else\n if brackets.empty?\n return false # There\'s no matching open bracket.\n end\n \n open_bracket = brackets.pop\n \n if (c == \')\' && open_bracket != \'(\') || (c == \'}\' && open_bracket != \'{\') || (c == \']\' && open_bracket != \'[\')\n return false # Mismatched closing bracket.\n end\n end\n end\n \n brackets.empty? # All open brackets should be closed.\nend\n\n```
1,988
Valid Parentheses
valid-parentheses
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if:
String,Stack
Easy
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g. { { } [ ] [ [ [ ] ] ] } is VALID expression [ [ [ ] ] ] is VALID sub-expression { } [ ] is VALID sub-expression Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g. { { ( { } ) } } |_| { { ( ) } } |______| { { } } |__________| { } |________________| VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
9,581
12
\n# Code\n```\nclass Solution:\n def isValid(self, s: str) -> bool:\n ack = []\n lookfor = {\')\':\'(\', \'}\':\'{\', \']\':\'[\'}\n\n for p in s:\n if p in lookfor.values():\n ack.append(p)\n elif ack and lookfor[p] == ack[-1]:\n ack.pop()\n else:\n return False\n\n return ack == []\n```
1,994
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
259,605
1,981
# 21. Merge Two Sorted Lists\n**KNOCKCAT**\n\n\n```\n1. Easy C++\n2. Line by Line Explanation with Comments.\n3. Detailed Explanation \u2705\n4. Linked list problem, merge.\n5. Please Upvote if it helps\u2B06\uFE0F\n6. Link to my Github Profile contains a repository of Leetcode with all my Solutions. \u2B07\uFE0F\n\t// \uD83D\uDE09If you Like the repository don\'t foget to star & fork the repository\uD83D\uDE09\n```\n\n[LeetCode]() **LINK TO LEETCODE REPOSITORY**\n\nPlease upvote my comment so that i get to win the 2022 giveaway and motivate to make such discussion post.\n**Happy new Year 2023 to all of you**\n**keep solving keep improving**\nLink To comment\n[Leetcode Give away comment]()\n\n**EXPLANATION**\n\n* Maintain a **head and a tail pointer** on the merged linked list. \n* Then choose the head of the merged linked list by comparing the first node of both linked lists.\n* For all subsequent nodes in both lists, you **choose the smaller current node** and l**ink it to the tail** of the merged list, and **moving the current pointer of that list one step forward.**\n\n* You **keep doing this while there are some remaining elements in both the lists.**\n* If there are **still some elements in only one of the lists**, you **link this remaining list to the tail of the merged list.**\n\n* Initially, the merged linked list is NULL.\n\n* **Compare the value of the first two nodes and make the node with the smaller value** the head node of the merged linked list.\n\n* Since it\u2019s the first and only node in the merged list, it will also be the tail.\n\n* Then **move head1 one step forward.**\n\n**Time Complexity O(n+m)**\n**Space Complexity O(n+m)** this is auxiliary stack space due to recursion.\n\n\n**RECURSIVE APPROACH**\n```\n\t\t\t\t\t// \uD83D\uDE09\uD83D\uDE09\uD83D\uDE09\uD83D\uDE09Please upvote if it helps \uD83D\uDE09\uD83D\uDE09\uD83D\uDE09\uD83D\uDE09\nclass Solution {\npublic:\n\tListNode* mergeTwoLists(ListNode* l1, ListNode* l2) \n {\n\t\t// if list1 happen to be NULL\n\t\t// we will simply return list2.\n\t\tif(l1 == NULL)\n {\n\t\t\treturn l2;\n\t\t}\n\t\t\n\t\t// if list2 happen to be NULL\n\t\t// we will simply return list1.\n\t\tif(l2 == NULL)\n {\n\t\t\treturn l1;\n\t\t} \n\t\t\n\t\t// if value pointend by l1 pointer is less than equal to value pointed by l2 pointer\n\t\t// we wall call recursively l1 -> next and whole l2 list.\n\t\tif(l1 -> val <= l2 -> val)\n {\n\t\t\tl1 -> next = mergeTwoLists(l1 -> next, l2);\n\t\t\treturn l1;\n\t\t}\n\t\t// we will call recursive l1 whole list and l2 -> next\n\t\telse\n {\n\t\t\tl2 -> next = mergeTwoLists(l1, l2 -> next);\n\t\t\treturn l2; \n\t\t}\n\t}\n};\t\n```\n\n**ITERATIVE APPROACH**\n\n**Time Complexity O(n+m)**\n**Space Complexity O(1)** \n\n```\n\t\t\t\t\t// \uD83D\uDE09\uD83D\uDE09\uD83D\uDE09\uD83D\uDE09Please upvote if it helps \uD83D\uDE09\uD83D\uDE09\uD83D\uDE09\uD83D\uDE09\nclass Solution {\npublic:\n ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {\n \n\t // if list1 happen to be NULL\n\t\t// we will simply return list2.\n if(list1 == NULL)\n return list2;\n\t\t\n\t\t// if list2 happen to be NULL\n\t\t// we will simply return list1.\n if(list2 == NULL)\n return list1;\n \n ListNode * ptr = list1;\n if(list1 -> val > list2 -> val)\n {\n ptr = list2;\n list2 = list2 -> next;\n }\n else\n {\n list1 = list1 -> next;\n }\n ListNode *curr = ptr;\n \n\t\t// till one of the list doesn\'t reaches NULL\n while(list1 && list2)\n {\n if(list1 -> val < list2 -> val){\n curr->next = list1;\n list1 = list1 -> next;\n }\n else{\n curr->next = list2;\n list2 = list2 -> next;\n }\n curr = curr -> next;\n \n }\n\t\t\n\t\t// adding remaining elements of bigger list.\n if(!list1)\n curr -> next = list2;\n else\n curr -> next = list1;\n \n return ptr;\n \n }\n};\n```
2,000
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
261,655
1,078
**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nFor simplicity, we create a dummy node to which we attach nodes from lists. We iterate over lists using two-pointers and build up a resulting list so that values are monotonically increased.\n\nTime: **O(n)**\nSpace: **O(1)**\n\n```\nclass Solution:\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n cur = dummy = ListNode()\n while list1 and list2: \n if list1.val < list2.val:\n cur.next = list1\n list1, cur = list1.next, list1\n else:\n cur.next = list2\n list2, cur = list2.next, list2\n \n if list1 or list2:\n cur.next = list1 if list1 else list2\n \n return dummy.next\n```\n\n**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**
2,001
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
82,147
494
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode mergeTwoLists(ListNode list1, ListNode list2) {\n\n if(list1!=null && list2!=null){\n if(list1.val<list2.val){\n list1.next=mergeTwoLists(list1.next,list2);\n return list1;\n }\n else{\n list2.next=mergeTwoLists(list1,list2.next);\n return list2;\n }\n }\n if(list1==null)\n return list2;\n return list1;\n }\n}\n```\n![7abc56.jpg]()\n
2,002
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
55,160
313
If you like it pls upvote\n```\n\n\n public ListNode mergeTwoLists(ListNode l1, ListNode l2) {\n ListNode prehead = new ListNode(-1);\n ListNode cur = prehead;\n\n while (l1 != null && l2 != null) {\n if (l1.val <= l2.val) {\n cur.next = l1;\n l1 = l1.next;\n } else {\n cur.next = l2;\n l2 = l2.next;\n }\n cur = cur.next;\n }\n\n cur.next = l1 == null ? l2 : l1;\n return prehead.next;\n }\n\n```
2,003
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
15,662
125
\n\nWe\'ll create a starting node called `head` and use a pointer called `current` to traverse the two lists. At each iteration of the loop, we compare the values of the nodes at list1 and list2, and point `current.next` to the <i>smaller</i> node. Then we advance the pointers and repeat until one of the list pointers reaches the end of the list.\n\nAt this point, there\'s no need to iterate through the rest of the other list because we know that it\'s still in sorted order. So `current.next = list1 or list2` points current.next to the list that still has nodes left. The last step is just to return `head.next`, since head was just a placeholder node and the actual list starts at `head.next`.\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution(object):\n def mergeTwoLists(self, list1, list2):\n head = ListNode()\n current = head\n while list1 and list2:\n if list1.val < list2.val:\n current.next = list1\n list1 = list1.next\n else:\n current.next = list2\n list2 = list2.next\n current = current.next\n\n current.next = list1 or list2\n return head.next\n```
2,004
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
235,906
1,413
public ListNode mergeTwoLists(ListNode l1, ListNode l2){\n \t\tif(l1 == null) return l2;\n \t\tif(l2 == null) return l1;\n \t\tif(l1.val < l2.val){\n \t\t\tl1.next = mergeTwoLists(l1.next, l2);\n \t\t\treturn l1;\n \t\t} else{\n \t\t\tl2.next = mergeTwoLists(l1, l2.next);\n \t\t\treturn l2;\n \t\t}\n }
2,005
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
30,518
184
To solve this problem, we can use **recursion**, calling it until one of the sheets is **null**, and while it is not null, we do an **equality check**, if list1 is less than or equal to list2, we call recursion with **list1.next** = mergeTwoLists (**list1.next**, list2), else if the value is greater than **list2.next** = mergeTwoLists(list1, **list2.next**). If one of the sheets is null, we simply return the opposite list **(we don\'t care if it\'s null or not**). Thus, when the recursion ends, the stack will begin to collapse in reverse order, which will allow us to get a new merged sorted list.\n\nI hope the picture below helps you understand better.\n\n![image]()\n![image]()\n\n**Time Complexity:** Since we\'re completely going through two lists. Thus, the time complexity is **O(m+n)**, where m and n are the lengths of the two lists to be combined.\n\n```\nvar mergeTwoLists = function (l1, l2) {\n if (!l1) return l2;\n else if (!l2) return l1;\n else if (l1.val <= l2.val) {\n l1.next = mergeTwoLists(l1.next, l2);\n return l1;\n } else {\n l2.next = mergeTwoLists(l1, l2.next);\n return l2\n }\n};\n```\n\nI hope I was able to explain clearly.\n**Happy coding!** \uD83D\uDE43
2,008
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
39,656
484
[Linkedlists]() can be confusing especially if you\'ve recently started to code but (I think) once you understand it fully, it should not be that difficult. \n\nFor this problem, I\'m going to explain several ways of solving it **BUT** I want to make something clear. Something that you\'ve seen a lot of times in the posts on this website but probably haven\'t fully understood. `dummy` variable! It has been used significantly in the solutions of this problem and not well explained for a newbie level coder! The idea is we\'re dealing with `pointers` that point to a memory location! Think of it this way! You want to find gold that is hidden somewhere. Someone has put a set of clues in a sequence! Meaning, if you find the first clue and solve the problem hidden in the clue, you will get to the second clue! Solving the hidden problem of second clue will get you to the thrid clue, and so on! If you keep solving, you\'ll get to the gold! `dummy` helps you to find the first clue!!!! \n\nThroughout the solution below, you\'ll be asking yourself why `dummy` is not changing and we eventually return `dummy.next`???? It doesn\'t make sense, right? However, if you think that `dummy` is pointing to the start and there is another variable (`temp`) that makes the linkes from node to node, you\'ll have a better filling! \nSimilar to the gold example if I tell you the first clue is at location X, then, you can solve clues sequentially (because of course you\'re smart) and bingo! you find the gold! Watch [this](). \n\nThis video shows why we need the `dummy`! Since we\'re traversing using `temp` but once `temp` gets to the tail of the sorted merged linkedlist, there\'s no way back to the start of the list to return as a result! So `dummy` to the rescue! it does not get changed throughout the list traversals `temp` is doing! So, `dummy` makes sure we don\'t loose the head of the thread (result list). Does this make sense? Alright! Enough with `dummy`! \n\nI think if you get this, the first solution feels natural! Now, watch [this](). You got the idea?? Nice! \n\n\nFirst you initialize `dummy` and `temp`. One is sitting at the start of the linkedlist and the other (`temp`) is going to move forward find which value should be added to the list. Note that it\'s initialized with a value `0` but it can be anything! You initialize it with your value of choice! Doesn\'t matter since we\'re going to finally return `dummy.next` which disregards `0` that we used to start the linkedlist. Line `#1` makes sure none of the `l1` and `l2` are empty! If one of them is empty, we should return the other! If both are nonempty, we check `val` of each of them to add the smaller one to the result linkedlist! In line `#2`, `l1.val` is smaller and we want to add it to the list. How? We use `temp` POINTER (it\'s pointer, remember that!). Since we initialized `temp` to have value `0` at first node, we use `temp.next` to point `0` to the next value we\'re going to add to the list `l1.val` (line `#3`). Once we do that, we update `l1` to go to the next node of `l1`. If the `if` statement of line `#2` doesn\'t work, we do similar stuff with `l2`. And finally, if the length of `l1` and `l2` are not the same, we\'re going to the end of one of them at some point! Line `#5` adds whatever left from whatever linkedlist to the `temp.next` (check the above video for a great explanation of this part). Note that both linkedlists were sorted initially. Also, this line takes care of when one of the linkedlists are empty. Finally, we return `dummy.next` since `dummy` is pointing to `0` and `next` to zero is what we\'ve added throughout the process. \n\n```\nclass Solution:\n def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: \n dummy = temp = ListNode(0)\n while l1 != None and l2 != None: #1\n\n if l1.val < l2.val: #2\n temp.next = l1 #3\n l1 = l1.next #4\n else: \n temp.next = l2\n l2 = l2.next\n temp = temp.next\n temp.next = l1 or l2 #5\n return dummy.next #6\n```\n\n\nAnother way of solving is problem is by doing recursion. This is from [here]((iteratively-recursively-iteratively-in-place)). The first check is obvious! If one of them is empty, return the other one! Similar to line `#5` of previous solution. Here, we have two cases, whatever list has the smaller first element (equal elements also satisfies line `#1`), will be returned at the end. In the example `l1 = [1,2,4], l2 = [1,3,4]`, we go in the `if` statement of line `#1` first, this means that the first element of `l1` doesn\'t get changed! Then, we move the pointer to the second element of `l1` by calling the function again but with `l1.next` and `l2` as input! This round of call, goes to line `#2` because now we have element `1` from `l2` versus `2` from `l1`. Now, basically, `l2` gets connected to the tail of `l1`. We keep moving forward by switching between `l1` and `l2` until the last element. Sorry if it\'s not clear enough! I\'m not a fan of recursion for such a problems! But, let me know which part it\'s hard to understand, I\'ll try to explain better! \n\n```\nclass Solution:\n def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: \n if not l1 or not l2:\n return l1 or l2\n \n if l1.val <= l2.val: #1\n l1.next = self.mergeTwoLists(l1.next, l2)\n return l1\n else: #2\n l2.next = self.mergeTwoLists(l1, l2.next)\n return l2\n```\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n===============================================================\nFinal note: Please let me know if you want me to explain anything in more detail. \n
2,009
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
821
7
# Intuition\n<!-- Your intuition or thoughts about solving the problem -->\nMy intuition is to merge two sorted linked lists into a single sorted linked list while keeping track of the current nodes in both input lists.\n\n# Approach\n<!-- Describe your approach to solving the problem -->\n1. Initialize a new linked list named `merged`.\n2. Initialize a temporary node `temp` pointing to `merged`.\n3. While both `l1` and `l2` are not empty:\n - Compare the values of the current nodes in `l1` and `l2`.\n - If `l1.val` is less than `l2.val`, set `temp.next` to `l1` and move `l1` to the next node.\n - If `l1.val` is greater than or equal to `l2.val`, set `temp.next` to `l2` and move `l2` to the next node.\n - Move `temp` to the next node.\n4. After the loop, if there are remaining nodes in `l1`, append them to `temp.next`.\n5. If there are remaining nodes in `l2`, append them to `temp.next`.\n6. Return the `next` node of `merged` as the merged linked list.\n\n# Complexity\n- Time complexity:\n - The while loop iterates through both linked lists, and each step involves constant-time operations.\n - The time complexity is O(n), where n is the total number of nodes in the two linked lists.\n\n- Space complexity:\n - Your code uses a constant amount of extra space for variables (`merged` and `temp`), and the space complexity is O(1).\n\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:\n merged = ListNode()\n temp = merged\n\n while l1 and l2 :\n if l1.val < l2.val :\n temp.next = l1\n l1 = l1.next\n else :\n temp.next = l2\n l2 = l2.next\n\n temp = temp.next\n\n if l1:\n temp.next = l1\n else :\n temp.next = l2\n\n return merged.next \n\n```\n\n# Please upvote the solution if you understood it.\n![1_3vhNKl1AW3wdbkTshO9ryQ.jpg]()\n
2,010
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
4,075
14
\n\n# Single Linked List----->Time : O(N)\n```\nclass Solution:\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n out=dummy=ListNode()\n while list1 and list2:\n if list1.val<list2.val:\n out.next=list1\n list1=list1.next\n else:\n out.next=list2\n list2=list2.next\n out=out.next\n if list1:\n out.next=list1\n list1=list1.next\n if list2:\n out.next=list2\n list2=list2.next\n return dummy.next\n\n```\n# please upvote me it would encourage me alot\n
2,011
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
174,293
977
\n \n # iteratively\n def mergeTwoLists1(self, l1, l2):\n dummy = cur = ListNode(0)\n while l1 and l2:\n if l1.val < l2.val:\n cur.next = l1\n l1 = l1.next\n else:\n cur.next = l2\n l2 = l2.next\n cur = cur.next\n cur.next = l1 or l2\n return dummy.next\n \n # recursively \n def mergeTwoLists2(self, l1, l2):\n if not l1 or not l2:\n return l1 or l2\n if l1.val < l2.val:\n l1.next = self.mergeTwoLists(l1.next, l2)\n return l1\n else:\n l2.next = self.mergeTwoLists(l1, l2.next)\n return l2\n \n # in-place, iteratively \n def mergeTwoLists(self, l1, l2):\n if None in (l1, l2):\n return l1 or l2\n dummy = cur = ListNode(0)\n dummy.next = l1\n while l1 and l2:\n if l1.val < l2.val:\n l1 = l1.next\n else:\n nxt = cur.next\n cur.next = l2\n tmp = l2.next\n l2.next = nxt\n l2 = tmp\n cur = cur.next\n cur.next = l1 or l2\n return dummy.next
2,012
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
1,493
7
\n\n# Code\n```\n\nclass Solution {\n public ListNode mergeTwoLists(ListNode list1, ListNode list2) {\n ListNode head = new ListNode();\n ListNode tail = head;\n while(list1 != null && list2!= null)\n {\n if(list1.val < list2.val)\n {\n tail.next = list1;\n list1 = list1.next;\n tail = tail.next;\n }\n else\n {\n tail.next = list2;\n list2 = list2.next;\n tail = tail.next;\n }\n }\n\n tail.next = (list1 != null) ? list1: list2;\n return head.next;\n\n }\n}\n```\n
2,014
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
29,477
97
**IF YOU FIND THIS POST HELPFUL PLEASE UPVOTE**\n\nVisit this blog to learn Python tips and techniques and to find a Leetcode solution with an explanation: \n\n**Solution:**\n```\nclass Solution:\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n newHead = dummyHead = ListNode()\n while list1 and list2:\n if list1.val < list2.val:\n dummyHead.next = list1\n list1 = list1.next\n else:\n dummyHead.next = list2\n list2 = list2.next\n dummyHead = dummyHead.next\n \n if list1:\n dummyHead.next = list1\n if list2:\n dummyHead.next = list2\n return newHead.next\n```\n**Thank you for reading! \uD83D\uDE04 Comment if you have any questions or feedback.**
2,021
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
627
5
# Intuition\n<!-- Your intuition or thoughts about solving the problem -->\nMy intuition is to merge two sorted linked lists into a single sorted linked list while keeping track of the current nodes in both input lists.\n\n# Approach\n<!-- Describe your approach to solving the problem -->\n1. Initialize a new linked list named `merged` and a temporary node `temp` pointing to `merged`.\n2. Check if either `l1` or `l2` is empty. If one of them is empty, return the other list, as there is no need to merge.\n3. While both `l1` and `l2` are not empty:\n - Compare the values of the current nodes in `l1` and `l2`.\n - If `l1->val` is less than `l2->val`, set `temp->next` to `l1` and move `l1` to the next node.\n - If `l1->val` is greater than or equal to `l2->val`, set `temp->next` to `l2` and move `l2` to the next node.\n - Move `temp` to the next node.\n4. After the loop, if there are remaining nodes in `l1`, append them to `temp->next`.\n5. If there are remaining nodes in `l2`, append them to `temp->next`.\n6. Return the `next` node of `merged` as the merged linked list.\n\n# Complexity\n- Time complexity:\n - The while loop iterates through both linked lists, and each step involves constant-time operations.\n - The time complexity is O(n), where n is the total number of nodes in the two linked lists.\n\n- Space complexity:\n - Your code uses a constant amount of extra space for variables (`merged`, `temp`), and the space complexity is O(1). However, it allocates new\n\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {\n ListNode* merged = new ListNode();\n ListNode* temp = merged;\n\n if(l1 == NULL){\n return l2;\n }\n\n if(l2 == NULL){\n return l1;\n }\n\n \n\n while(l1 != NULL && l2 != NULL){\n if(l1->val < l2->val){\n temp->next = l1;\n l1 = l1->next ;\n }\n else {\n temp->next = l2;\n l2 = l2->next;\n }\n temp = temp->next;\n }\n\n if(l1 == NULL){\n temp->next = l2;\n }\n else{\n temp->next = l1;\n }\n \n\n return merged->next;\n \n }\n};\n```\n\n# Please upvote the solution if you understood it.\n![1_3vhNKl1AW3wdbkTshO9ryQ.jpg]()\n
2,024
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
40,525
475
My first solution is an iterative one. One thing deserves discussion is whether we should create a new `ListNode` as a convenient way to hold the list. Sometimes, in industrial projects, sometimes it's not trivial to create a `ListNode` which might require many resource allocations or inaccessible dependencies (we need to mock them).\n\nSo ideally, we should pick up either the head of l1 or l2 as the head other than creating a new one, which however makes the initialization step tedious. \n\nBut during an interview, I would rather create a new `ListNode` as list holder, but communicate with the interviewer that I'm aware of the potential issue, and would improve it if he/she thinks this is a big deal. \n\n```java\npublic class Solution {\n public ListNode mergeTwoLists(ListNode l1, ListNode l2) {\n ListNode head = new ListNode(0);\n ListNode handler = head;\n while(l1 != null && l2 != null) {\n if (l1.val <= l2.val) {\n handler.next = l1;\n l1 = l1.next;\n } else {\n handler.next = l2;\n l2 = l2.next;\n }\n handler = handler.next;\n }\n \n if (l1 != null) {\n handler.next = l1;\n } else if (l2 != null) {\n handler.next = l2;\n }\n \n return head.next;\n }\n}\n```\n\n-----\nMy second solution is to use recursion. Personally, I don't like this approach. Because in real life, the length of a linked list could be much longer than we expected, in which case the recursive approach is likely to introduce a stack overflow. (Imagine a file system)\n\nBut anyway, as long as we communicate this concerning properly with the interviewer, I don't think it's a big deal here.\n\n```java\npublic class Solution {\n public ListNode mergeTwoLists(ListNode l1, ListNode l2) {\n if (l1 == null) return l2;\n if (l2 == null) return l1;\n \n ListNode handler;\n if(l1.val < l2.val) {\n handler = l1;\n handler.next = mergeTwoLists(l1.next, l2);\n } else {\n handler = l2;\n handler.next = mergeTwoLists(l1, l2.next);\n }\n \n return handler;\n }\n}\n```
2,025
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
17,618
41
# Intuition:\nThe problem requires us to merge two sorted linked lists into a new sorted linked list. We can achieve this by comparing the values of the head nodes of the two linked lists and adding the smaller one to our new merged linked list. We can repeat this process by advancing the pointer of the smaller element and comparing it with the other linked list\'s head node\'s value, and we continue this process until we exhaust all the nodes in both lists. This way, we can obtain a new linked list containing all the elements of both linked lists in a sorted order.\n\n# Approach:\n\n- **Recursive Approach:**\nThe recursive approach is based on the idea that we compare the values of the first nodes of the two lists, and whichever has the smaller value, we add that node to our merged linked list and call the same function recursively with the next node of that list and the other list\'s current node. We repeat this process until one of the lists exhausts, and we return the merged list.\n\n- **Iterative Approach:**\nThe iterative approach is based on the same idea as the recursive approach. Here, we maintain three pointers: one for the merged linked list\'s head, one for the current node of the merged list, and one for the current node of each of the two input linked lists. We compare the two lists\' head nodes and add the smaller one to our merged linked list and advance the pointer of that list. We continue this process until we exhaust one of the input lists, and then we add the remaining nodes of the other list to our merged linked list.\n\n# Complexity:\n\n- Time complexity: Both approaches take O(n+m) time, where n and m are the sizes of the two linked lists because we iterate through all the nodes of both linked lists at most once.\n\n- Space complexity: Recursive approach has a space complexity of O(n+m) due to the recursive stack space, while the iterative approach has a space complexity of O(1) since we are using constant space for storing the merged linked list.\n# C++\n- ### Code: Recursive Approach \n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {\n ListNode* ptr1 = list1;\n ListNode* ptr2 = list2;\n if(ptr1 == NULL){\n return list2;\n }\n if(ptr2 == NULL){\n return list1;\n }\n if(ptr1->val < ptr2->val){\n ptr1->next = mergeTwoLists(ptr1->next, ptr2);\n return ptr1;\n }\n else{\n ptr2->next = mergeTwoLists(ptr1, ptr2->next);\n return ptr2;\n }\n }\n};\n```\n- ### Code: Iterative Approach\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {\n ListNode* ans = new ListNode();\n ListNode* ptr = ans;\n while(list1 && list2){\n if(list1->val <= list2->val){\n ans->next = new ListNode(list1->val);\n list1 = list1->next;\n }\n else{\n ans->next = new ListNode(list2->val);\n list2 = list2->next;\n }\n ans = ans->next;\n }\n while(list1){\n ans->next = new ListNode(list1->val);\n list1 = list1->next;\n ans = ans->next;\n }\n while(list2){\n ans->next = new ListNode(list2->val);\n list2 = list2->next;\n ans = ans->next;\n }\n return ptr->next;\n }\n};\n```\n\n---\n\n# JavaScript\n- ### Code: Recursive Approach \n```\n/**\n * Definition for singly-linked list.\n * function ListNode(val) {\n * this.val = val;\n * this.next = null;\n * }\n */\n/**\n * @param {ListNode} l1\n * @param {ListNode} l2\n * @return {ListNode}\n */\nvar mergeTwoLists = function(l1, l2) {\n if (!l1) return l2;\n if (!l2) return l1;\n if (l1.val < l2.val) {\n l1.next = mergeTwoLists(l1.next, l2);\n return l1;\n } else {\n l2.next = mergeTwoLists(l1, l2.next);\n return l2;\n }\n};\n\n```\n- ### Code: Iterative Approach\n```\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} list1\n * @param {ListNode} list2\n * @return {ListNode}\n */\nvar mergeTwoLists = function(list1, list2) {\n let ans = new ListNode();\n let ptr = ans;\n while(list1 && list2){\n if(list1.val <= list2.val){\n ans.next = new ListNode(list1.val);\n list1 = list1.next;\n }\n else{\n ans.next = new ListNode(list2.val);\n list2 = list2.next;\n }\n ans = ans.next;\n }\n while(list1){\n ans.next = new ListNode(list1.val);\n list1 = list1.next;\n ans = ans.next;\n }\n while(list2){\n ans.next = new ListNode(list2.val);\n list2 = list2.next;\n ans = ans.next;\n }\n return ptr.next;\n};\n\n```\n\n---\n\n# JAVA\n- ### Code: Recursive Approach \n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode mergeTwoLists(ListNode list1, ListNode list2) {\n if (list1 == null) return list2;\n if (list2 == null) return list1;\n if (list1.val < list2.val) {\n list1.next = mergeTwoLists(list1.next, list2);\n return list1;\n } else {\n list2.next = mergeTwoLists(list1, list2.next);\n return list2;\n }\n }\n}\n\n```\n- ### Code: Iterative Approach\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode mergeTwoLists(ListNode list1, ListNode list2) {\n ListNode ans = new ListNode();\n ListNode ptr = ans;\n while(list1 != null && list2 != null){\n if(list1.val <= list2.val){\n ans.next = new ListNode(list1.val);\n list1 = list1.next;\n }\n else{\n ans.next = new ListNode(list2.val);\n list2 = list2.next;\n }\n ans = ans.next;\n }\n while(list1 != null){\n ans.next = new ListNode(list1.val);\n list1 = list1.next;\n ans = ans.next;\n }\n while(list2 != null){\n ans.next = new ListNode(list2.val);\n list2 = list2.next;\n ans = ans.next;\n }\n return ptr.next;\n }\n}\n\n```\n\n---\n\n# Python\n### Code: Recursive Approach \n```\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n\nclass Solution(object):\n def mergeTwoLists(self, l1, l2):\n """\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n """\n if not l1: return l2\n if not l2: return l1\n if l1.val < l2.val:\n l1.next = self.mergeTwoLists(l1.next, l2)\n return l1\n else:\n l2.next = self.mergeTwoLists(l1, l2.next)\n return l2\n\n```\n- ### Code: Iterative Approach\n```\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution(object):\n def mergeTwoLists(self, list1, list2):\n """\n :type list1: Optional[ListNode]\n :type list2: Optional[ListNode]\n :rtype: Optional[ListNode]\n """\n ans = ListNode()\n ptr = ans\n while list1 and list2:\n if list1.val <= list2.val:\n ans.next = ListNode(list1.val)\n list1 = list1.next\n else:\n ans.next = ListNode(list2.val)\n list2 = list2.next\n ans = ans.next\n while list1:\n ans.next = ListNode(list1.val)\n list1 = list1.next\n ans = ans.next\n while list2:\n ans.next = ListNode(list2.val)\n list2 = list2.next\n ans = ans.next\n return ptr.next\n```\n
2,026
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
4,570
6
# Intuition\nThis question is asking you to merge 2 linked lists and return the head.\n\nThink of this question like you are inserting values between the head and the tail of a new empty list.\n\nWe start off by initalizing a head and movingtail to ListNode(). This makes head and tail both equal to an empty node. the head variable is commonly used and called the "dummy node". \n\nNext we loop through both lists and compare values to see which one is greater as we must merge both lists in increasing value. i named movingtail movingtail because it moves while head stays in place. Everytime one of the linked list nodes is greater than the other the tail moves/sets the next node equal to the "greater node" (movingtail.next = l1) and the "greater node" moves to the next node in that linked list. \n\nIf either linked list is empty this runs: (movingtail.next = l1 or l2) which sets movingtail equal to the linked list that isn\'t empty. \n\nAt the end of the program head.next returns, which means that the head or dummy node\'s next value (the head) will get returned which is the answer to the question.\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n head = movingtail = ListNode()\n \n while l1 and l2:\n if l1.val <= l2.val:\n movingtail.next = l1\n l1 = l1.next\n else:\n movingtail.next = l2\n l2 = l2.next\n movingtail = movingtail.next\n \n movingtail.next = l1 or l2\n return head.next\n```
2,032
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
110,531
575
class Solution {\n public:\n ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {\n ListNode dummy(INT_MIN);\n ListNode *tail = &dummy;\n \n while (l1 && l2) {\n if (l1->val < l2->val) {\n tail->next = l1;\n l1 = l1->next;\n } else {\n tail->next = l2;\n l2 = l2->next;\n }\n tail = tail->next;\n }\n \n tail->next = l1 ? l1 : l2;\n return dummy.next;\n }\n };
2,033
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
9,189
52
\n\n# Complexity\n- Time complexity: O(m+n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {\n \n if(l1 == NULL) return l2;\n if(l2 == NULL) return l1;\n\n\n if(l1->val > l2->val){ // taking L1 is smaller than l2 \n swap(l1,l2); // haar baar l1 hi chota hoga\n }\n ListNode* result = l1;\n ListNode* temp = NULL;\n while(l1 != NULL && l2 != NULL){\n \n if(l1->val <= l2->val ){\n temp = l1;\n l1 = l1->next;\n }\n else {\n temp -> next = l2;\n swap(l1,l2); // haar baar l1 hi chota hoga\n }\n }\n while(l1 != NULL){\n temp->next = l1;\n temp = l1;\n l2 = l2->next;\n }\n while(l2 != NULL){\n temp->next = l2;\n temp = l2;\n l2 = l2 ->next;\n }\n \n return result;\n }\n};\n```\n![7abc56.jpg]()\n
2,038
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
475
6
```\nclass Solution:\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n dummy = ListNode(0)\n curr = dummy\n while list1 and list2:\n if list1.val > list2.val:\n curr.next = list2\n list2 = list2.next\n else:\n curr.next = list1\n list1 = list1.next\n curr = curr.next\n \n curr.next = list1 or list2\n \n return dummy.next\n```
2,039
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
5,674
10
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode mergeTwoLists(ListNode list1, ListNode list2) {\n if(list1!=null && list2!=null)\n {\n if(list1.val < list2.val)\n {\n list1.next = mergeTwoLists(list1.next,list2);\n return list1;\n }\n else\n {\n list2.next = mergeTwoLists(list1,list2.next);\n return list2;\n }\n }\n if(list1 == null)\n return list2;\n return list1; \n }\n}\n```
2,040
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
2,077
14
Please upvote :)\n```\nclass Solution:\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n newHead = dummyHead = ListNode()\n while list1 and list2:\n if list1.val < list2.val:\n dummyHead.next = list1\n list1 = list1.next\n else:\n dummyHead.next = list2\n list2 = list2.next\n dummyHead = dummyHead.next\n \n if list1:\n dummyHead.next = list1\n if list2:\n dummyHead.next = list2\n return newHead.next\n\n```
2,050
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
71,076
475
**Solution 1**\n\nIf both lists are non-empty, I first make sure `a` starts smaller, use its head as result, and merge the remainders behind it. Otherwise, i.e., if one or both are empty, I just return what's there.\n\n class Solution:\n def mergeTwoLists(self, a, b):\n if a and b:\n if a.val > b.val:\n a, b = b, a\n a.next = self.mergeTwoLists(a.next, b)\n return a or b\n\n---\n\n**Solution 2**\n\nFirst make sure that `a` is the "better" one (meaning `b` is None or has larger/equal value). Then merge the remainders behind `a`.\n\n def mergeTwoLists(self, a, b):\n if not a or b and a.val > b.val:\n a, b = b, a\n if a:\n a.next = self.mergeTwoLists(a.next, b)\n return a
2,051
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
4,037
7
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince both lists are sorted, I use the two-pointers method and run a loop on both lists and compare it, and put the smaller value in a newly formed list.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode mergeTwoLists(ListNode list1, ListNode list2) {\n ListNode h = new ListNode(0);\n ListNode tail = h;\n \n while(list1 != null && list2 != null){\n if(list1.val < list2.val){\n tail.next = list1;\n list1 = list1.next;\n tail = tail.next;\n }else{\n tail.next = list2;\n list2 = list2.next;\n tail = tail.next;\n }\n }\n\n while(list1 != null){\n tail.next = list1;\n list1 = list1.next;\n tail = tail.next;\n\n }\n\n while(list2 != null){\n tail.next = list2;\n list2 = list2.next;\n tail = tail.next;\n\n }\n\n return h.next;\n\n }\n}\n```
2,058
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
776
5
# Intuition\nFirst, We don\'t need to add value in the newly created linked list, we simply need to change the node pointers from one value to another.\n\n# Approach\n1. If any one of the linked list out of the two given linked list is empty then simply return the other linked list which is not empty. // if(l1==NULL) return l2; if(l2==NULL) return l1;\n2. Declare another linked list l3 to store the answer. // ListNode* l3 = new ListNode(0)\n3. Take one head or dummy pointer pointing to the head of the answer linked list. // ListNode* Head = l3;\n4. Run a loop untill any one of l1 or l2 becomes Null. while(l1 && l2)\n5. if (l1->val<=l2->val) then make l3->next=l1; then make l3=l3->next; and l1=l1->next\n6. else if(l1->val>l2->val) then make l3->next= l2; then make l3=l3->next; and l2=l2->next;\n7. Lastly if any one of either l1 or l2 has more nodes left then simply run two seperate while loops each for l1 and l2.\n8. While(l1) { l3->next=l1; l3=l3->next; l1=l1->next;}\n9. while(l2) {l3->next=l2; l3=l3->next; l2=l2->next;}\n10. return Head->next;\n\n# Complexity\n- Time complexity:\n0(n)\n\n- Space complexity:\n0(1)\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {\n if(l1 == NULL)\n return l2;\n if(l2 == NULL)\n return l1;\n ListNode* l3=new ListNode(0);\n ListNode* Head = l3;\n while(l1 && l2)\n {\n if(l1->val<=l2->val)\n {\n l3->next=l1;\n l3=l3->next;\n l1=l1->next;\n }\n else \n {\n l3->next =l2;\n l3=l3->next;\n l2=l2->next;\n }\n }\n while(l1)\n {\n l3->next=l1;\n l3=l3->next;\n l1=l1->next;\n }\n while(l2)\n {\n l3->next=l2;\n l3=l3->next;\n l2=l2->next;\n }\n return Head->next;\n\n }\n};\n```
2,065
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
1,092
15
# Intuition\n\nMerging two sorted linked lists involves comparing the values of nodes from both lists and creating a new merged list. We can iterate through the lists while comparing their values, appending the smaller value node to the merged list, and moving the corresponding pointer forward in that list. By repeating this process, we construct the merged list.\n\n# Approach\nCreate a dummy node to serve as the starting point of the merged list.\nInitialize a current pointer (head) to the dummy node.\nUse a while loop to iterate while both list1 and list2 have nodes.\nCompare the values of the current nodes in list1 and list2.\nAppend the smaller value node to the head.next and move the corresponding pointer forward in that list.\nContinue this process until one of the lists becomes empty.\nAttach the remaining non-null list to the end of the merged list.\nReturn dummy.next as the merged list, which is the actual starting node.\n\n# Complexity\n- Time complexity:\nO(m + n), where m and n are the lengths of list1 and list2 respectively, as we iterate through both lists once.\n\n- Space complexity:\nO(1), as we are only using a constant amount of extra space for the dummy node and the head pointer.\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode mergeTwoLists(ListNode list1, ListNode list2) {\n\n \n ListNode temp = new ListNode(-5);\n \n \n ListNode head = temp;\n\n \n while (list1 != null && list2 != null) {\n \n if (list1.val <= list2.val) {\n head.next = list1;\n \n list1 = list1.next;\n } else {\n \n head.next = list2;\n \n list2 = list2.next;\n }\n \n head = head.next;\n }\n\n \n if (list1 != null) {\n head.next = list1;\n } else {\n head.next = list2;\n }\n \n \n return temp.next;\n }\n}\n\n\n\n```\n![c0504eaf-5fb8-4a1d-a769-833262d1b86e_1674433591.3836212.webp]()
2,067
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
2,642
13
```python\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n dummy = ListNode(0) # making a dummy node\n curr = dummy # creating a pointer pointing to the dummy node\n \n while list1 and list2: # we must be having both list to perform merge operation.\n if list1.val < list2.val: # in case list value is less then list2,\n curr.next = list1 # then we move our pointer ahead in list 1.\n list1 = list1.next # having value of next element of list2\n else:\n curr.next = list2 # in case list2 value is greaer then list 1 value.\n list2 = list2.next #having value of next element of list2\n curr = curr.next # moving our curr pointer\n \n # In case all the elements of any one of the list is travered. then we`ll move our pointer to the left over. \n # As lists are soted already, technically we could do that\n # Method : 1\n# if list1:\n# curr.next = list1\n# elif list2:\n# curr.next = list2\n \n # Method : 2\n curr.next = list1 or list2\n \n return dummy.next # return next bcz first node is dummy. \n```\n***Found helpful, Do upvote !!***
2,068
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
519
6
\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {\n //return the head of list2 if list1 does not exist\n if(list1==NULL)\n return list2;\n //return the head of list1 if list2 does not exist\n if(list2==NULL)\n return list1;\n\n if(list1->val <= list2->val){\n list1->next = mergeTwoLists(list1->next, list2);\n return list1;\n }\n else{\n list2->next = mergeTwoLists(list1, list2->next);\n return list2;\n }\n }\n};\n/**/\n```
2,072
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
3,224
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe above solution implements the merging of two sorted linked lists. The intuition is to compare the first elements of both the lists and add the smallest element to the merged list and update the corresponding pointer to that list. This process continues until all the elements of either of the lists are merged.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach used is to iterate over the two lists simultaneously and keep adding the smaller element to the merged list. At each step, the corresponding pointer is updated and the iteration continues until all the elements are merged. Finally, if any elements are remaining in either of the lists, they are added to the merged list.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n+m) where n and m are the lengths of the input lists as both lists are traversed once. \n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1) as we are not using any additional data structures. We only use constant extra space to store the pointers and the merged list.\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode mergeTwoLists(ListNode list1, ListNode list2) {\n ListNode p1 = list1;\n ListNode p2 = list2;\n ListNode fakeHead = new ListNode(0);\n ListNode p = fakeHead;\n while(p1 != null && p2 != null)\n {\n if(p1.val <= p2.val)\n {\n p.next = p1;\n p1 = p1.next;\n }\n else\n {\n p.next = p2;\n p2 = p2.next;\n }\n p = p.next;\n }\n if(p1 != null)\n p.next = p1;\n if(p2 != null)\n p.next = p2;\n return fakeHead.next;\n }\n \n}\n```
2,074
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
1,416
11
**Explanation**\nHere we initialise two Linked List, one cur and another result with 0.\nWe use cur to connect all the nodes of two list in sorted way. The result is only use to remember the head of cur List.\nCur list not just take one node, instead it simply merges the whole list l1 or l2 and then increase the pointer.\n```\nclass Solution:\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n # iteratively\n result = cur = ListNode(0)\n l1=list1\n l2=list2\n while l1 and l2:\n if l1.val < l2.val:\n cur.next = l1\n l1 = l1.next\n else:\n cur.next = l2\n l2 = l2.next\n cur = cur.next\n cur.next = l1 or l2\n return result.next\n\n```\n![image]()\n![image]()\n![image]()\n![image]()\n\n
2,075
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
2,401
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode mergeTwoLists(ListNode list1, ListNode list2) {\n while(list1 != null && list2 != null) {\n if(list1.val <= list2.val) {\n list1.next = mergeTwoLists(list1.next, list2);\n return list1;\n } else {\n list2.next = mergeTwoLists(list2.next, list1);\n return list2;\n }\n }\n return list1 == null ? list2 : list1;\n }\n}\n```
2,077
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
523
9
**Easy Solution for this problem**\n```\nclass Solution {\n public ListNode mergeTwoLists(ListNode list1, ListNode list2) {\n if(list1 == null) return list2;\n if(list2 == null) return list1;\n \n if(list1.val<list2.val){\n list1.next = mergeTwoLists(list1.next, list2);\n return list1;\n }else{\n list2.next = mergeTwoLists(list2.next, list1);\n return list2;\n }\n }\n}\n``\n\n
2,085
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
3,372
9
# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode mergeTwoLists(ListNode list1, ListNode list2) {\n ListNode mergedList = new ListNode(0);\n ListNode result = mergedList;\n\n while (list1 != null && list2 != null) {\n if (list1.val < list2.val) {\n mergedList.next = new ListNode(list1.val);\n list1 = list1.next;\n } else {\n mergedList.next = new ListNode(list2.val);\n list2 = list2.next;\n }\n mergedList = mergedList.next;\n }\n\n if (list1 != null) {\n mergedList.next = list1;\n } else {\n mergedList.next = list2;\n }\n\n return result.next;\n }\n}\n```
2,088
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
101,148
376
class Solution {\n public:\n ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {\n if(l1 == NULL) return l2;\n if(l2 == NULL) return l1;\n \n if(l1->val < l2->val) {\n l1->next = mergeTwoLists(l1->next, l2);\n return l1;\n } else {\n l2->next = mergeTwoLists(l2->next, l1);\n return l2;\n }\n }\n };\n\n\nThis solution is not a tail-recursive, the stack will overflow while the list is too long :)\n
2,089
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
10,269
25
\n# Approach\n1. Create a new node called tempNode and set its value to 0 and its next pointer to null.\n2. Set currentNode to tempNode.\n3. While l1 and l2 are not null, compare the values of the nodes pointed to by l1 and l2. Add the smaller value node to currentNode and move the corresponding pointer to its next node.\n4. Set the next pointer of currentNode to the remaining nodes of l1 or l2.\n5. Return the merged list starting from the next node of tempNode, which is tempNode.next.\n\n# Complexity\n\nThe time complexity of the iterative approach is O(m + n), where m and n are the lengths of l1 and l2, respectively. This is because we iterate over both lists once and compare each node at most once.\n\nThe space complexity of the iterative approach is O(1), since we only create a constant number of new nodes (tempNode and currentNode) and modify the pointers of the input lists in place. Therefore, the space required is constant and does not depend on the length of the input lists.\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode} list1\n * @param {ListNode} list2\n * @return {ListNode}\n */\n\nvar mergeTwoLists = function(l1, l2) {\n let tempNode = new ListNode(0, null);\n let currentNode = tempNode;\n \n while (l1 && l2) {\n if(l1.val < l2.val) {\n currentNode.next = l1;\n l1 = l1.next\n } else {\n currentNode.next = l2;\n l2 = l2.next\n }\n currentNode = currentNode.next;\n }\n currentNode.next = l1 || l2;\n \n return tempNode.next;\n};\n\n```
2,092
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists list1 and list2. Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list.
Linked List,Recursion
Easy
null
1,889
34
# Summary\n\n* No recursion and therefore O(1) space complexity. \n* No memory allocations --> Splicing as required by problem description\n* Optimal run-time complexity O(n). \n\nThe code speaks for itself. \n\n# Code\n```\nimpl Solution {\n pub fn merge_two_lists(\n mut l1: Option<Box<ListNode>>,\n mut l2: Option<Box<ListNode>>,\n ) -> Option<Box<ListNode>> {\n let mut r = &mut l1;\n while l2.is_some() {\n if r.is_none() || l2.as_ref()?.val < r.as_ref()?.val {\n std::mem::swap(r, &mut l2);\n }\n r = &mut r.as_mut()?.next;\n }\n l1\n }\n}\n```
2,099
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
97,050
1,292
1. The idea is to add `\')\'` only after valid `\'(\'`\n2. We use two integer variables `left` & `right` to see how many `\'(\'` & `\')\'` are in the current string\n3. If `left < n` then we can add `\'(\'` to the current string\n4. If `right < left` then we can add `\')\'` to the current string\n\n**Python Code:**\n```\ndef generateParenthesis(self, n: int) -> List[str]:\n\tdef dfs(left, right, s):\n\t\tif len(s) == n * 2:\n\t\t\tres.append(s)\n\t\t\treturn \n\n\t\tif left < n:\n\t\t\tdfs(left + 1, right, s + \'(\')\n\n\t\tif right < left:\n\t\t\tdfs(left, right + 1, s + \')\')\n\n\tres = []\n\tdfs(0, 0, \'\')\n\treturn res\n```\n\nFor` n = 2`, the recursion tree will be something like this,\n```\n\t\t\t\t\t\t\t\t \t(0, 0, \'\')\n\t\t\t\t\t\t\t\t \t |\t\n\t\t\t\t\t\t\t\t\t(1, 0, \'(\') \n\t\t\t\t\t\t\t\t / \\\n\t\t\t\t\t\t\t(2, 0, \'((\') (1, 1, \'()\')\n\t\t\t\t\t\t\t / \\\n\t\t\t\t\t\t(2, 1, \'(()\') (2, 1, \'()(\')\n\t\t\t\t\t\t / \\\n\t\t\t\t\t(2, 2, \'(())\') (2, 2, \'()()\')\n\t\t\t\t\t\t |\t |\n\t\t\t\t\tres.append(\'(())\') res.append(\'()()\')\n \n```\n\n**Java Code:**\n```java\nclass Solution {\n public List<String> generateParenthesis(int n) {\n List<String> res = new ArrayList<String>();\n recurse(res, 0, 0, "", n);\n return res;\n }\n \n public void recurse(List<String> res, int left, int right, String s, int n) {\n if (s.length() == n * 2) {\n res.add(s);\n return;\n }\n \n if (left < n) {\n recurse(res, left + 1, right, s + "(", n);\n }\n \n if (right < left) {\n recurse(res, left, right + 1, s + ")", n);\n }\n }\n\t// See above tree diagram with parameters (left, right, s) for better understanding\n}\n```\n![image]()\n\n\n![image]()\n\n\n\n
2,100
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
28,256
285
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem is one of the classical recursion problems. \nFor any given n, lets say n = 2, we have to fill four places in our output ("_ _ _ _"). And each of these places can be either filled by an open braces "(" or a closed braces ")". \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n "_ _ _ _"\n / \\ \n \'(\' \')\'\n\nFor every place we have two choices and 1 decision to make. \nOur choices are to either use \'(\' or \')\'.\n\nNow lets try to visualize the recursive tree based upon the choices discussed above.\n\nInitially, we have:\nFor n = 3\ncurrent ouput = ""\navailableOpenBracketsCnt = 3 and availableCloseBracketsCnt = 3\n\nThe first choise is very simple. Since we can not start a balanced parenthesis sequence with \')\', we have only one choice in the begining. So our output will be \'(\' and count of open brackets left = 2 and count of closed brackets left = 3.\n\n op ip\n "" O-3, C-3\n \n "(",O-2,C-3\n \n "((",O-1,C-3 "()", O-2,C-2\n\n "(((",0,3 "(()",1,2 "()(",1,2\n\n "((()",0,2 "(()(",0,2 "(())",1,1 "()((",0,2 "()()",1,1\n\n "((())",0,1 "(()()",0,1 "(())(",0,1 "()(()",0,1 "()()(",0,1\n\n "((()))",0,0 "(()())",0,0 "(())()",0,0 "()(())",0,0 "()()()", 0,0\n \n\n# Observation from the recursive tree\n\n - Whenever we have count of open brackets equal to the count of close brackets, we have only one choice - that is to use \'(\'. Because, all the brackets till now have been balanced. And we can not start a new sequence with \')\'. \n - Whenever, count of close bracket is 0, we can only use \'(\'.\n - Whenever, count of open bracket is 0, we can only use \')\'.\n - And for all the remaining cases, we have both the choices.\n - We get an answer, when count of open == 0 and count of close == 0.\n\nJust convert these 5 observations into an algorithm and write the code. \n\n\n# Code\n```\nclass Solution {\npublic:\n void solve(string op, int open, int close, vector<string> &ans){\n if(open == 0 && close == 0){\n ans.push_back(op);\n return;\n }\n //when count of open and close brackets are same then \n //we have only one choice to put open bracket \n if(open == close){\n string op1 = op;\n op1.push_back(\'(\');\n solve(op1, open-1, close, ans);\n }\n else if(open == 0){\n //only choice is to put close brackets \n string op1 = op;\n op1.push_back(\')\');\n solve(op1, open, close-1, ans);\n }\n else if(close == 0){\n //only choise is to use open bracket \n string op1 = op;\n op1.push_back(\'(\');\n solve(op1, open-1, close, ans);\n }\n else{\n string op1 = op;\n string op2 = op;\n op1.push_back(\'(\');\n op2.push_back(\')\');\n solve(op1, open-1, close, ans);\n solve(op2, open, close-1, ans);\n }\n }\n vector<string> generateParenthesis(int n) {\n int open = n;\n int close = n;\n vector<string> ans;\n string op = "";\n solve(op, open, close, ans);\n return ans;\n }\n};\n```\n**Note** : I have kept the code implementation simple by just following the observations I mentioned. The same code can be made more compact by reducing some conditional statements (although the time and space complexity will remain the same).\nTry to come up with your own compact version. Refer the comments of other peers for help.\n\n# Complexity Analysis: \n- Time Complexity : $O(N*2^N)$ where N = 2*n\n $O(2^N)$ : We have N = 2n places to fill and for every place we will have a maximum of 2 choices. \n $O(N)$ : We will have to multiply our TC by a factor of N, as every time when we hit the base case, we will copy current op (which is of size N) into the answer vector.\n- Space Complexity : $O(N)$ + Recursive Stack Space\n We have used an extra string of size N for storing current output\n# Please upvote the solution if you understood it.\n\n![NRRa.gif]()\n\n**You can connect with me on linkedin, If you understood my solution :D**\n\n\n
2,101
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
5,563
55
UPVOTE IT TO KEEP IT AT THE TOP!\n\n# Intuition\nThis code aims to generate all valid combinations of balanced parentheses pairs given a positive integer n. The goal is to produce all possible strings of length 2*n, where each character is either \'(\' or \')\', and the resulting strings are valid parentheses expressions.\n\n# Approach\nThe code uses a recursive approach to generate these combinations. The solve function is called recursively to build the strings while maintaining the count of open and closed parentheses. Here\'s how it works:\n\nThe base case is when the index ind reaches or exceeds n * 2. At this point, the constructed string op is a valid combination of parentheses, so it\'s added to the result vector ans.\n\nIf the count of open parentheses cnt1 is less than n and the current index ind is less than n * 2 - 1, a \'(\' character is added to the string op, and the solve function is called recursively with cnt1 incremented by 1 and the index increased by 1.\n\nIf the count of closed parentheses cnt2 is less than cnt1 and the current index ind is greater than 0, a \')\' character is added to the string op, and the solve function is called recursively with cnt2 incremented by 1 and the index increased by 1.\n\nAfter each recursive call, the last character is removed from the string op using op.pop_back() to backtrack and explore different combinations.\n\nThe generateParenthesis function initializes the result vector ans and calls the solve function with initial counts and index.\n\n# Complexity\n- Time complexity: O(4^n / sqrt(n))\nTime complexity: The recursive approach explores all possible combinations, and the total number of valid combinations is bounded by the nth Catalan number, which grows exponentially with n. Thus, the time complexity is exponential, approximately O(4^n / sqrt(n)).\n\n- Space complexity: O(n)\nSpace complexity: The space complexity is determined by the maximum recursion depth, which is proportional to n. Additionally, the space used by the string op in each recursive call contributes to the space complexity. Therefore, the space complexity is O(n) due to the recursion depth.\n\n\n![5d0bae9a5411b.jpeg]()\n\n\n# Code\n```\nclass Solution {\n private:\n void solve(int cnt1,int cnt2,int n,vector<string> &ans,string &op,int ind)\n {\n if(ind>=n*2)\n {\n ans.push_back(op);\n return;}\n if(cnt1<n and ind<n*2-1)\n {\n op+=\'(\';\n solve(cnt1+1,cnt2,n,ans,op,ind+1);\n op.pop_back();\n }\n \n if(cnt2<cnt1 and ind>0)\n {\n op+=\')\';\n \n solve(cnt1,cnt2+1,n,ans,op,ind+1);\n op.pop_back();\n }\n \n }\npublic:\n vector<string> generateParenthesis(int n) {\n string op="";\n vector<string> ans;\n solve(0,0,n,ans,op,0);\n return ans;\n }\n};\n\n\n\n\n
2,108
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
228,996
1,374
public List<String> generateParenthesis(int n) {\n List<String> list = new ArrayList<String>();\n backtrack(list, "", 0, 0, n);\n return list;\n }\n \n public void backtrack(List<String> list, String str, int open, int close, int max){\n \n if(str.length() == max*2){\n list.add(str);\n return;\n }\n \n if(open < max)\n backtrack(list, str+"(", open+1, close, max);\n if(close < open)\n backtrack(list, str+")", open, close+1, max);\n }\n\nThe idea here is to only add '(' and ')' that we know will guarantee us a solution (instead of adding 1 too many close). Once we add a '(' we will then discard it and try a ')' which can only close a valid '('. Each of these steps are recursively called.
2,112
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
6,840
32
\n```\nclass Solution {\n public List<String> generateParenthesis(int n) {\n List<String> res = new ArrayList();\n findAll("(",1,0,res,n);\n\n return res;\n }\n\n void findAll(String current,int op , int cl , List<String> res, int n){\n if(current.length()==2*n){\n res.add(current);\n return;\n }\n if(op<n)\n findAll(current+"(", op+1,cl,res,n);\n if(cl<op)\n findAll(current+")",op,cl+1,res,n);\n }\n}\n```
2,114
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
19,717
241
**Intuition:** Since we are asked to calculate all the possible permutations of brackets , hence we have to use backtracking\n\n**Concept:** In every backtracking problem , there are two things to keep in mind , which we will explore here as well :\n* Base Case: Every problem of backtracking has some base case which tells us at which point we have to stop with the recursion process. In our case, when the length of our string has reached the maximum length(`n*2`), we stop with the recursion for that case and that is our base case.\n\n* Conditions: On observing carefully we find that there are two conditions present:\n * For adding **`(`**: If number of opening brackets(`open`) is less than the the given length(`n`) i.e.\n if `max`<`n`, then we can add **`(`**,else not.\n\t* For adding **`)`**: If number of close brackets(`close`) is less than the opening brackets(`open`), i.e.\n\t if `open`<`close`, we can add **`)`**, else not\n\t\t\nAnd thats it!!! Keeping these two things in mind here is the code: \n\n**Code:**\n\n```\nclass Solution {\npublic:\n vector<string>result;\n \n void helper(int open,int close,int n,string current)\n {\n if(current.length()==n*2)\n {\n result.push_back(current);\n return;\n }\n if(open<n) helper(open+1,close,n,current+"(");\n if(close<open) helper(open,close+1,n,current+")");\n }\n vector<string> generateParenthesis(int n) {\n helper(0,0,n,"");\n return result;\n }\n};\n```\n\n**For similar problems: [Backtracking Collection]()**\n\nIf you like, please **UPVOTE**\nHappy Coding :))
2,123
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
3,118
13
The idea is intuitive. Use two integers to count the remaining left parenthesis (left) and the right parenthesis (right) to be added.\n**At each function call add a left parenthesis and add a right parenthesis if right>left. Add the result if left==0 and right==0.**\n\n```\nclass Solution {\npublic:\n vector<string> ans;\n \n void fun(int left,int right,string s)\n {\n if(left<0||right<0)\n {\n return;\n }\n if(left==0 and right==0)\n {\n ans.push_back(s);\n return;\n }\n \n fun(left-1,right,s+"(");\n\t \n if(right>left)\n\t {\n\t fun(left,right-1,s+")");\n\t }\n }\n \n vector<string> generateParenthesis(int n) {\n fun(n,n,"");\n return ans;\n }\n};
2,124
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
110,583
717
The idea is intuitive. Use two integers to count the remaining left parenthesis (n) and the right parenthesis (m) to be added. At each function call add a left parenthesis if n >0 and add a right parenthesis if m>0. Append the result and terminate recursive calls when both m and n are zero.\n\n class Solution {\n public:\n vector<string> generateParenthesis(int n) {\n vector<string> res;\n addingpar(res, "", n, 0);\n return res;\n }\n void addingpar(vector<string> &v, string str, int n, int m){\n if(n==0 && m==0) {\n v.push_back(str);\n return;\n }\n if(m > 0){ addingpar(v, str+")", n, m-1); }\n if(n > 0){ addingpar(v, str+"(", n-1, m+1); }\n }\n };
2,125
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
4,933
20
\n# Code\n```\nclass Solution {\npublic:\n void solve(string op, int open, int close, vector<string> &ans){\n if(open == 0 && close == 0){\n ans.push_back(op);\n return;\n }\n //when count of open and close brackets are same then \n //we have only one choice to put open bracket \n if(open == close){\n string op1 = op;\n op1.push_back(\'(\');\n solve(op1, open-1, close, ans);\n }\n else if(open == 0){\n //only choice is to put close brackets \n string op1 = op;\n op1.push_back(\')\');\n solve(op1, open, close-1, ans);\n }\n else if(close == 0){\n //only choise is to use open bracket \n string op1 = op;\n op1.push_back(\'(\');\n solve(op1, open-1, close, ans);\n }\n else{\n string op1 = op;\n string op2 = op;\n op1.push_back(\'(\');\n op2.push_back(\')\');\n solve(op1, open-1, close, ans);\n solve(op2, open, close-1, ans);\n }\n }\n vector<string> generateParenthesis(int n) {\n int open = n;\n int close = n;\n vector<string> ans;\n string op = "";\n solve(op, open, close, ans);\n return ans;\n }\n};\n```
2,126
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
1,593
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nKch ni krna hai, ye socho ki obviously open bracket close bracket se pehle aaega, to condition open bracket ka lekr chalna hai, or bs code kr dena hai\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nOpen bracket daalo, close bracket daalo, jb open N se aage jae ya close open se aage jae to ruk jaana hai, ni to 3 condition likha hai, dekho samjh aa jaega\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nNI PTA, SAARA TEST CASE PASS HO GAYA HAI\n<!-- Contact : c0deblooded telegram username -->\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nAB RETURN KRNA HAI TO ANS STRING TO BNANA PADEGA NA BHAI\n# Code\n```\nclass Solution {\npublic:\n vector<string>ans;\n\n void solve(int n, string &str, int open, int close){\n if(open == close and open == n - 1){\n ans.push_back(str);\n return;\n }\n if(open < n){\n str.push_back(\'(\');\n solve(n, str, open + 1, close);\n str.pop_back();\n\n }\n if(open > close){\n str.push_back(\')\');\n solve(n, str, open, close + 1);\n str.pop_back();\n }\n }\n\n vector<string> generateParenthesis(int n) {\n ans.clear();\n ans.resize(0);\n string str;\n solve(n+1, str, 0, 0);\n return ans;\n }\n};\n```
2,129
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
6,899
20
# Intuition:\nThe problem requires generating all possible combinations of well-formed parentheses of length 2n. To solve this, we can use a recursive approach. At each step, we have two choices: either add an opening parenthesis "(" or add a closing parenthesis ")". However, we need to make sure that the number of opening parentheses is always greater than or equal to the number of closing parentheses, so that the parentheses remain well-formed.\n\n# Approach:\n1. We define a helper function, `generateParentheses`, that takes the following parameters:\n - `result`: a reference to the vector of strings where we store the generated combinations.\n - `current`: the current combination being generated.\n - `open`: the count of opening parentheses "(" included in the current combination.\n - `close`: the count of closing parentheses ")" included in the current combination.\n - `n`: the total number of pairs of parentheses to be included.\n\n2. In the `generateParentheses` function, we first check if the length of the `current` string is equal to 2n. If it is, we have generated a valid combination, so we add it to the `result` vector and return.\n\n3. If the length of `current` is not equal to 2n, we have two choices:\n - If the count of opening parentheses `open` is less than n, we can add an opening parenthesis to the current combination and make a recursive call to `generateParentheses`, incrementing the `open` count by 1.\n - If the count of closing parentheses `close` is less than the `open` count, we can add a closing parenthesis to the current combination and make a recursive call to `generateParentheses`, incrementing the `close` count by 1.\n\n4. In the `generateParenthesis` function, we initialize an empty `result` vector and call the `generateParentheses` function with the initial values of `current` as an empty string, `open` and `close` counts as 0, and `n` as the input value.\n\n5. Finally, we return the `result` vector containing all the generated combinations of well-formed parentheses.\n\n# Complexity:\nThe time complexity of this solution is O(4^n / sqrt(n)), where n is the input number of pairs of parentheses.\nThe space complexity of this solution is O(n). \n\n---\n# C++\n```\nclass Solution {\npublic:\n void generateParentheses(vector<string>& result, string current, int open, int close, int n) {\n if (current.size() == 2 * n) {\n result.push_back(current);\n return;\n }\n if (open < n) {\n generateParentheses(result, current + \'(\', open + 1, close, n);\n }\n if (close < open) {\n generateParentheses(result, current + \')\', open, close + 1, n);\n }\n }\n vector<string> generateParenthesis(int n) {\n vector<string> result;\n generateParentheses(result, "", 0, 0, n);\n return result;\n }\n};\n```\n---\n# JAVA\n```\nclass Solution {\n public List<String> generateParenthesis(int n) {\n List<String> result = new ArrayList<>();\n generateParentheses(result, "", 0, 0, n);\n return result;\n }\n\n private void generateParentheses(List<String> result, String current, int open, int close, int n) {\n if (current.length() == 2 * n) {\n result.add(current);\n return;\n }\n if (open < n) {\n generateParentheses(result, current + \'(\', open + 1, close, n);\n }\n if (close < open) {\n generateParentheses(result, current + \')\', open, close + 1, n);\n }\n }\n}\n\n```\n\n---\n# Python\n```\nclass Solution(object):\n def generateParenthesis(self, n):\n result = []\n self.generateParentheses(result, "", 0, 0, n)\n return result\n\n def generateParentheses(self, result, current, open, close, n):\n if len(current) == 2 * n:\n result.append(current)\n return\n if open < n:\n self.generateParentheses(result, current + \'(\', open + 1, close, n)\n if close < open:\n self.generateParentheses(result, current + \')\', open, close + 1, n)\n\n```\n\n---\n# JavaScript\n```\nvar generateParenthesis = function(n) {\n const result = [];\n generateParentheses(result, \'\', 0, 0, n);\n return result;\n};\n\nconst generateParentheses = (result, current, open, close, n) => {\n if (current.length === 2 * n) {\n result.push(current);\n return;\n }\n if (open < n) {\n generateParentheses(result, current + \'(\', open + 1, close, n);\n }\n if (close < open) {\n generateParentheses(result, current + \')\', open, close + 1, n);\n }\n};\n```
2,130
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
1,868
8
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n void fnc(vector<string> &ans,int n,int open,int close,string curr_str){\n if(curr_str.size()==n*2){\n ans.push_back(curr_str);\n return;\n }\n if(open<n){\n fnc(ans,n,open+1,close,curr_str +\'(\');\n }\n if(close<open){\n fnc(ans,n,open,close+1,curr_str +\')\');\n }\n }\npublic:\n vector<string> generateParenthesis(int n) {\n vector<string> ans;\n fnc(ans,n,0,0,"");\n return ans;\n }\n};\n```\nPlease upvote to motivate me to write more solutions\n\n
2,142
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
5,665
53
Hello all, \n\nBefore jumping to the code, go through the explanation. I have curated the explanation for your easy understanding. This will help you build a clear logic for many recursive problems moving forward.\n\nStep1: Identification of Problem\nThe problem asks us to generate all the valid paranthesis sequences, the first thing that should come to mind is recursion. Hence recursion is the way forward. \n\nStep2: Correctness of Solution\nIt is really crucial to understand that the solution should be correct befire being optimized. \n\nStep3: Building Solution \nWe start by maintaining a count for both the opening and closing paranthesis as\n```\n// count1 is used to flag the base case \n// count2 is used to react to the base case \ncount1=0 and count2=0 respectively.\n\n// following is the signature for the recursive function\nsubseq(int count1,int count2,string v,vector<string> &ans,int n)\n\n// only the first three parameters are determining the state of each recursive call.\n// vector<string> &ans is passed with every recursive call to store the final valid strings\n// int n is used to check the base condition\n```\n\nStep 4: Logic\n\n* A Valid sequence will include the closing paranthesis only when there are more opening paranthesis. Hence, the condition\n```\nif(count2<count1){\n\tsubseq(count1,count2+1,v+")",ans,n); \n}\n```\n* An opening paranthesis is always open to be the part of a valid paranthesis till it has a count less than n. \n* As soon as the count of opening paranthesis reaches n, we push all the remaining closing paranthesis into the sequence, because there are no more opening paranthesis to add.\n\nStep5: Code\n```\nvoid subseq(int count1,int count2,string v,vector<string> &ans,int n){\n if(count1==n){\n // if there are n open \'(\', we simply push the rest closing \')\'\n while(count2<n){\n v+=")";\n count2+=1;\n }\n\t\t\t// v is pushed to the answer vector\n\t\t\t\n ans.push_back(v);\n return;\n }\n\t\t\n subseq(count1+1,count2,v+"(",ans,n);\n\t\t\n if(count2<count1){\n subseq(count1,count2+1,v+")",ans,n); \n }\n }\n vector<string> generateParenthesis(int n) {\n vector<string> ans;\n string v;\n subseq(0,0,v,ans,n);\n\n return ans;\n }\n```\n\n**Please upvote, if the solution was of help to you. This will help other people in the community optimize their search for the best solution.**\n\nCheers!!\n\n\n\n
2,145
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
343
6
# **PLS UPVOTE IF YOU LIKE MY SOLUTION AND COMMENT FOR ANY DISCUSSION **\n# Approach\nFunction solve: This is a recursive helper function that generates all valid combinations of parentheses.\n\nThe base case is when the length of the temp string becomes equal to 2 * n. At this point, you\'ve formed a valid combination, so you add it to the result vector and return.\n\nIf you can still add an opening parenthesis ( (i.e., if start < n), you recursively call solve with an incremented start and append an opening parenthesis to the temp string.\n\nIf you can add a closing parenthesis ) without making the combination invalid (i.e., if close < start), you recursively call solve with an incremented close and append a closing parenthesis to the temp string.\n\nFunction generateParenthesis: This is the main function that initializes the result vector and starts the recursion by calling the solve function.\n\nThe initial call to solve has start and close both set to 0, and an empty temp string.\nThe idea behind this approach is to generate all possible combinations of parentheses by recursively adding an opening parenthesis when possible and a closing parenthesis when it won\'t lead to an invalid combination. The recursion explores all possible paths of forming valid combinations.\n\nThe result will be a vector of strings containing all the valid combinations of parentheses for the given n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(2^(2n))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:0(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\nvoid solve(int n , int start , int close, string temp ,vector<string>&result)\n{\n if(temp.size()==n*2)\n {\n result.push_back(temp);\n return ; \n }\n if(start < n)\n {\n solve(n,start + 1, close,temp + "(", result);\n }\n if(close < start )\n {\n solve(n,start, close + 1,temp + ")", result);\n }\n }\n vector<string> generateParenthesis(int n) {\n vector<string>result;\n solve(n,0, 0,"", result);\n return result;\n }\n};\n```
2,147
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
1,985
5
# Intuition\n \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n void helper(vector<string> &v, int n, int oc, int cc, string s)\n {\n if(oc==n && cc==n){\n v.push_back(s);\n return ;\n }\n if(oc<n){\n helper(v,n,oc+1,cc,s+"(");\n }\n if(cc < oc){\n helper(v,n,oc, cc+1, s+")");\n }\n\n }\n vector<string> generateParenthesis(int n) {\n vector<string> v;\n int oc=0, cc=0;\n helper(v,n,oc,cc,"");\n return v;\n }\n};\n```
2,148
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
96,959
429
`p` is the parenthesis-string built so far, `left` and `right` tell the number of left and right parentheses still to add, and `parens` collects the parentheses.\n\n**Solution 1**\n\nI used a few "tricks"... how many can you find? :-)\n\n def generateParenthesis(self, n):\n def generate(p, left, right, parens=[]):\n if left: generate(p + '(', left-1, right)\n if right > left: generate(p + ')', left, right-1)\n if not right: parens += p,\n return parens\n return generate('', n, n)\n\n**Solution 2**\n\nHere I wrote an actual Python generator. I allow myself to put the `yield q` at the end of the line because it's not that bad and because in "real life" I use Python 3 where I just say `yield from generate(...)`.\n\n def generateParenthesis(self, n):\n def generate(p, left, right):\n if right >= left >= 0:\n if not right:\n yield p\n for q in generate(p + '(', left-1, right): yield q\n for q in generate(p + ')', left, right-1): yield q\n return list(generate('', n, n))\n\n**Solution 3**\n\nImproved version of [this](). Parameter `open` tells the number of "already opened" parentheses, and I continue the recursion as long as I still have to open parentheses (`n > 0`) and I haven't made a mistake yet (`open >= 0`).\n\n def generateParenthesis(self, n, open=0):\n if n > 0 <= open:\n return ['(' + p for p in self.generateParenthesis(n-1, open+1)] + \\\n [')' + p for p in self.generateParenthesis(n, open-1)]\n return [')' * open] * (not n)
2,149
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
1,650
6
# Complexity\n- Time complexity: O(4^n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(4^n*n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n void solve(int open, int close, vector<string>& ans, string s) {\n if (open == 0 && close == 0) {\n ans.push_back(s);\n return;\n }\n if (open > 0) solve(open - 1, close, ans, s + \'(\');\n if (close > 0 && close > open) solve(open, close - 1, ans, s + \')\');\n }\n vector<string> generateParenthesis(int n) {\n vector<string> ans;\n solve(n, n, ans, "");\n return ans;\n }\n};\n```
2,150
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
1,308
6
# Intuition\nGenerate every possible string using recursion and check each string is valid or not.\n\n# Complexity\n- Time complexity:\nO(2^(2n)*2n).\n# Code\n```\nclass Solution {\npublic:\n bool isvalid(string &s){\n stack<char> st;\n for(int i=0;i<s.length();i++){\n if(s[i]==\'(\') st.push(\'(\');\n else {\n if(!st.empty()) st.pop();\n else return false;\n }\n }\n if(st.size()==0) return true;\n return false;\n \n }\n \n void solve(int n1,int n2,string s,vector<string> &ans){\n if(n1==0 && n2==0){\n if(isvalid(s)){\n ans.push_back(s);\n }\n return;\n }\n if(n1!=0) {s.push_back(\'(\'); solve(n1-1,n2,s,ans); s.pop_back();}\n \n if(n2!=0) {s.push_back(\')\'); solve(n1,n2-1,s,ans);}\n \n \n \n}\n\n vector<string> generateParenthesis(int n) {\n\n vector<string> ans;\n solve(n,n,"",ans);\n return ans;\n \n }\n};\n```
2,155
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
2,629
11
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\ninitially we have number of open bracket is n and closed is also n.\n\nnow we can add \'(\' in the resultant string(i.e s) without any condition and Decrease the count for this and make the recursive call.\n\nbut to add \')\' in the resultant string there is a condition. the condition is we can add \')\' only when the no of open bracket (i.e noOfOpenBracket) is less then the no of closed bracket\n (i.e noOfCloseBracket) because all the closed bracket should make pair with corresponding open bracket.\n\nmeans for n=3 the string "( ) ****)**** ( ( )" is not valid beacuse the 2nd closed bracket doesn\'t have the corresponding open bracket before it\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n vector<string> ans;\n void workfunc(int noOfOpenBracket,int noOfCloseBracket,string s)\n {\n if(noOfOpenBracket==0 && noOfCloseBracket==0)\n {\n ans.push_back(s);\n return;\n }\n if(noOfOpenBracket<noOfCloseBracket)\n {\n workfunc(noOfOpenBracket,noOfCloseBracket-1,s+\')\');\n }\n if(noOfOpenBracket>0)\n workfunc(noOfOpenBracket-1,noOfCloseBracket,s+\'(\');\n }\n \npublic:\n vector<string> generateParenthesis(int n) {\n workfunc(n,n,"");\n return ans;\n }\n};\n```
2,158
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
72,004
410
My method is DP. First consider how to get the result f(n) from previous result f(0)...f(n-1).\nActually, the result f(n) will be put an extra () pair to f(n-1). Let the "(" always at the first position, to produce a valid result, we can only put ")" in a way that there will be i pairs () inside the extra () and n - 1 - i pairs () outside the extra pair.\n\nLet us consider an example to get clear view:\n\nf(0): ""\n\nf(1): "("f(0)")"\n\nf(2): "("f(0)")"f(1), "("f(1)")"\n\nf(3): "("f(0)")"f(2), "("f(1)")"f(1), "("f(2)")"\n\nSo f(n) = "("f(0)")"f(n-1) , "("f(1)")"f(n-2) "("f(2)")"f(n-3) ... "("f(i)")"f(n-1-i) ... "(f(n-1)")"\n\nBelow is my code:\n\n public class Solution\n {\n public List<String> generateParenthesis(int n)\n {\n List<List<String>> lists = new ArrayList<>();\n lists.add(Collections.singletonList(""));\n \n for (int i = 1; i <= n; ++i)\n {\n final List<String> list = new ArrayList<>();\n \n for (int j = 0; j < i; ++j)\n {\n for (final String first : lists.get(j))\n {\n for (final String second : lists.get(i - 1 - j))\n {\n list.add("(" + first + ")" + second);\n }\n }\n }\n \n lists.add(list);\n }\n \n return lists.get(lists.size() - 1);\n }\n }
2,159
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
4,534
26
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can solve this problem using Array + Backtracking.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can easily understand the all the approaches by seeing the code which is easy to understand with comments.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTime complexity is given in code comment.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSpace complexity is given in code comment.\n\n# Code\n```\n/*\n\n Time Complexity : O((2^2*N)*N). For each of 2^2*N sequences, we need to create and validate the sequence,\n which takes O(N) work.\n\n Space Complexity : O((2^2*N)*N) vector(output) space.\n\n Solved using Array + Backtracking. Brute Force Approach.\n\n*/\n\n\n/***************************************** Approach 1 *****************************************/\n\nclass Solution {\nprivate:\n bool valid(vector<char> temp){\n int balance = 0;\n for(auto c : temp){\n if(c == \'(\') balance++;\n else balance--;\n if(balance < 0) return false;\n }\n return balance == 0;\n }\n void generateAllParenthesis(vector<string>& parenthesesCombinations, vector<char> temp, int position){\n if(position == temp.size()){\n if(valid(temp)){\n string s(temp.begin(), temp.end());\n parenthesesCombinations.push_back(s);\n }\n return;\n }\n temp[position] = \'(\';\n generateAllParenthesis(parenthesesCombinations, temp, position+1);\n temp[position] = \')\';\n generateAllParenthesis(parenthesesCombinations, temp, position+1); \n }\npublic:\n vector<string> generateParenthesis(int n) {\n vector<string> parenthesesCombinations;\n vector<char> temp(2*n);\n generateAllParenthesis(parenthesesCombinations, temp, 0);\n return parenthesesCombinations;\n }\n};\n\n\n\n\n\n\n/*\n\n Time Complexity : O(O(2^2*N)The time complexity of the above code is O(2^(2N)) since in the worst case we\n need to consider every possibility of opening and closing brackets where N = the number of pairs we need to\n form.\n\n Space Complexity : O((2^2*N)*N) vector(output) space.\n\n Solved using Array + Backtracking. Brute Force Approach.\n\n*/\n\n/***************************************** Approach 2 *****************************************/\n\nclass Solution {\nprivate:\n void recurse(vector<string>& output, string s, int open, int close, int n){\n if(open==n and close==n){\n output.push_back(s);\n return;\n }\n if(open<n)\n recurse(output, s+"(" , open+1, close, n);\n if(close<open)\n recurse(output, s+")", open, close+1, n);\n }\npublic:\n vector<string> generateParenthesis(int n) {\n vector<string> output;\n recurse(output, "", 0, 0, n);\n return output;\n }\n};\n\n```\n\n***IF YOU LIKE THE SOLUTION THEN PLEASE UPVOTE MY SOLUTION BECAUSE IT GIVES ME MOTIVATION TO REGULARLY POST THE SOLUTION.***\n\n![WhatsApp Image 2023-02-10 at 19.01.02.jpeg]()
2,164
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
39,337
314
To generate all n-pair parentheses, we can do the following:\n\n1. Generate one pair: ()\n2. Generate 0 pair inside, n - 1 afterward: () (...)...\n\n Generate 1 pair inside, n - 2 afterward: (()) (...)...\n\n ...\n\n Generate n - 1 pair inside, 0 afterward: ((...)) \n\nI bet you see the overlapping subproblems here. Here is the code:\n\n(you could see in the code that `x` represents one j-pair solution and `y` represents one (i - j - 1) pair solution, and we are taking into account all possible of combinations of them)\n\n class Solution(object):\n def generateParenthesis(self, n):\n """\n :type n: int\n :rtype: List[str]\n """\n dp = [[] for i in range(n + 1)]\n dp[0].append('')\n for i in range(n + 1):\n for j in range(i):\n dp[i] += ['(' + x + ')' + y for x in dp[j] for y in dp[i - j - 1]]\n return dp[n]
2,165
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
3,749
65
**\u2714\uFE0F Solution 1: Naive Backtracking**\n```python\nclass Solution:\n def generateParenthesis(self, n: int) -> List[str]:\n ans = []\n \n def isValidParenthesis(s):\n cntOpen = 0\n for c in s:\n if c == \'(\':\n cntOpen += 1\n else:\n if cntOpen == 0: return False # Don\'t have enough open to match with this close parentheses\n cntOpen -= 1\n return cntOpen == 0 #\xA0Fully match all open parentheses\n \n def bt(i, path):\n if i == 2 * n:\n if isValidParenthesis(path):\n ans.append(path)\n return\n \n bt(i+1, path + "(") # Add open\n bt(i+1, path + ")") # Add close\n \n bt(0, "")\n return ans\n```\nComplexity:\n- Time: `O(2^m * m)`, where `m = 2n`, `n <= 8`\n- Space: `n-th` Catalan Number.\n\n---\n**\u2714\uFE0F Solution 2: Smart Backtracking**\n```python\nclass Solution:\n def generateParenthesis(self, n: int) -> List[str]:\n def backtracking(nOpen, nClose, path):\n if n == nClose: # Found a valid n pairs of parentheses\n ans.append(path)\n return\n\n if nOpen < n: # Number of opening bracket up to `n`\n backtracking(nOpen + 1, nClose, path + "(")\n if nClose < nOpen: # Number of closing bracket up to opening bracket\n backtracking(nOpen, nClose + 1, path + ")")\n\n ans = []\n backtracking(0, 0, "")\n return ans\n```\n**Complexity**\n- Our complexity analysis based on how many elements there are in `generateParenthesis(n)`. \n- This is the `n-th` [Catalan number](), where the first Catalan numbers for `n = 0, 1, 2, 3, ...` are `1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786,...`\n- Time & Space: `n-th` Catalan Number.
2,167
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
1,323
6
# Approach\n<!-- Describe your approach to solving the problem. -->\n Backtracking\n\n# Code\n```\nclass Solution {\npublic:\n vector<string> ans;\n void solve(string &st, int fb, int sb, int mx) {\n if(st.size() == 2 * mx) {\n ans.push_back(st);\n return;\n }\n if(fb < mx) {\n st.push_back(\'(\');\n solve(st, fb+1, sb, mx);\n st.pop_back();\n }\n if(sb < fb) {\n st.push_back(\')\');\n solve(st, fb, sb+1, mx);\n st.pop_back();\n }\n }\n\n vector<string> generateParenthesis(int n) {\n string st;\n solve(st, 0, 0, n);\n return ans;\n }\n};\n```
2,168
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
1,388
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n void gp(int left,int right,string &s,vector<string> &ans){\n if(left==0 && right==0)\n ans.push_back(s);\n\n if(left>right || left<0 || right<0){\n return ;\n }\n s.push_back(\'(\');\n gp(left-1,right,s,ans);\n s.pop_back();\n\n s.push_back(\')\');\n gp(left,right-1,s,ans);\n s.pop_back();\n }\n vector<string> generateParenthesis(int n) {\n vector<string> ans;\n string s;\n gp(n,n,s,ans);\n return ans;\n }\n};\n/*UPVOTE IF THE SOLUTION WAS HELPFUL FOR YOU.*/\n```
2,175
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
6,115
61
One thing we need to understand is, we need a way to add \u201C(\u201D and \u201C)\u201D to all possible cases and \nthen find a way to validate so that we don\u2019t generate the unnecessary ones.\n\nThe first condition is if there are more than 0 open / left brackets, we recurse with the right\nones. And if we have more than 0 right brackets, we recurse with the left ones. Left and right\nare initialized with` \'n\' `- the number given.\n\n\n```\n\t\t\tif left>0:\n helper(ans, s+\'(\', left-1, right)\n \n if right>0:\n helper(ans, s+\')\', left, right-1)\n```\n\n<br>\n\nThere\u2019s a catch. We can\u2019t add the \u201C)\u201D everytime we have `right>0` cause then it will not be\nbalanced. We can balance that with a simple condition of `left<right.`\n\n```\n\t\t\tif left>0:\n helper(ans, s+\'(\', left-1, right)\n \n if right>0 and left<right:\n helper(ans, s+\')\', left, right-1)\n```\n\n<br>\nSince this is a recursive approach we need to have a **BASE condition**,\nand the base case is: \n\nWhen both right and left are 0, \nwe have found one possible combination of parentheses \n& we now need to append/add the `\'s\'` to `\'ans\'` list.\n\n```\n\t\t\tif left==0 and right==0:\n ans.append(s)\n```\n\n<br>\n<br>\n\n**Complete code**\n```\nclass Solution:\n def generateParenthesis(self, n: int) -> List[str]:\n \n \n def helper(ans, s, left, right):\n if left==0 and right==0:\n ans.append(s)\n \n if left>0:\n helper(ans, s+\'(\', left-1, right)\n \n if right>0 and left<right:\n helper(ans, s+\')\', left, right-1)\n \n ans = []\n helper(ans, \'\', n, n)\n \n return ans\n```\n\n\n\n<br>\n<br>\n*If this post seems to be helpful, please upvote!!*
2,183
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
455
6
```\nvoid generateParenthesis(int open, int close, string op, vector<string>& ans) {\n if(open == 0 && close == 0) {\n ans.push_back(op);\n return;\n }\n \n if(open > 0) generateParenthesis(open-1, close, op+"(", ans);\n \n if(close > open) generateParenthesis(open, close-1, op+")", ans);\n \n }\n \n vector<string> generateParenthesis(int n) {\n vector<string> ans;\n int open = n;\n int close = n;\n string op = "";\n generateParenthesis(open, close, op, ans);\n \n return ans;\n }\n```
2,188
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
39,790
221
If you have two stacks, one for n "(", the other for n ")", you generate a binary tree from these two stacks of left/right parentheses to form an output string. \n\n\nThis means that whenever you traverse deeper, you pop one parentheses from one of stacks. When two stacks are empty, you form an output string.\n\nHow to form a legal string? Here is the simple observation:\n\n - For the output string to be right, stack of ")" most be larger than stack of "(". If not, it creates string like "())"\n - Since elements in each of stack are the same, we can simply express them with a number. For example, left = 3 is like a stacks ["(", "(", "("]\n\nSo, here is my sample code in Python:\n\n class Solution:\n # @param {integer} n\n # @return {string[]}\n def generateParenthesis(self, n):\n if not n:\n return []\n left, right, ans = n, n, []\n self.dfs(left,right, ans, "")\n return ans\n\n def dfs(self, left, right, ans, string):\n if right < left:\n return\n if not left and not right:\n ans.append(string)\n return\n if left:\n self.dfs(left-1, right, ans, string + "(")\n if right:\n self.dfs(left, right-1, ans, string + ")")
2,191
Generate Parentheses
generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
String,Dynamic Programming,Backtracking
Medium
null
9,355
170
Generating all combinations of well formed paranthesis is a typical example of catalan numbers. You can use the links at the bottom here if you are not aware of the catalan numbers since they are at the heart of the exercise.\nLet time complexity for the generating all combinations of well-formed parentheses is f(n), then\nf(n) = g(n) * h(n) where g(n) is the time complexity for calculating nth catalan number, and h(n) is the time required to copy this combination to result array.\nTherefore, f(n) = catalan(n) * O(n) which is O(4^n/n^1.5)*(n)). Broadly saying just remember that this is a typical example of catalan number and it's time complexity is similar to how catalan(n) is got.\nFurther readings in to catalan numbers:\n\n\n
2,193
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
42,254
161
# Code\n\nPlease **Upvote** And **Comment** ....!\uD83D\uDE4F\uD83D\uDE4F\uD83D\uDE4F\n\n```JAVA []\nclass Solution {\n public ListNode mergeKLists(ListNode[] lists) {\n if (lists == null || lists.length == 0) {\n return null;\n }\n return mergeKListsHelper(lists, 0, lists.length - 1);\n }\n \n private ListNode mergeKListsHelper(ListNode[] lists, int start, int end) {\n if (start == end) {\n return lists[start];\n }\n if (start + 1 == end) {\n return merge(lists[start], lists[end]);\n }\n int mid = start + (end - start) / 2;\n ListNode left = mergeKListsHelper(lists, start, mid);\n ListNode right = mergeKListsHelper(lists, mid + 1, end);\n return merge(left, right);\n }\n \n private ListNode merge(ListNode l1, ListNode l2) {\n ListNode dummy = new ListNode(0);\n ListNode curr = dummy;\n \n while (l1 != null && l2 != null) {\n if (l1.val < l2.val) {\n curr.next = l1;\n l1 = l1.next;\n } else {\n curr.next = l2;\n l2 = l2.next;\n }\n curr = curr.next;\n }\n \n curr.next = (l1 != null) ? l1 : l2;\n \n return dummy.next;\n }\n}\n\n\n```\n```python []\nclass Solution:\n def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n if not lists:\n return None\n if len(lists) == 1:\n return lists[0]\n \n mid = len(lists) // 2\n left = self.mergeKLists(lists[:mid])\n right = self.mergeKLists(lists[mid:])\n \n return self.merge(left, right)\n \n def merge(self, l1, l2):\n dummy = ListNode(0)\n curr = dummy\n \n while l1 and l2:\n if l1.val < l2.val:\n curr.next = l1\n l1 = l1.next\n else:\n curr.next = l2\n l2 = l2.next\n curr = curr.next\n \n curr.next = l1 or l2\n \n return dummy.next\n```\n```C++ []\nclass Solution {\npublic:\n ListNode* mergeKLists(vector<ListNode*>& lists) {\n if (lists.empty()) {\n return nullptr;\n }\n return mergeKListsHelper(lists, 0, lists.size() - 1);\n }\n \n ListNode* mergeKListsHelper(vector<ListNode*>& lists, int start, int end) {\n if (start == end) {\n return lists[start];\n }\n if (start + 1 == end) {\n return merge(lists[start], lists[end]);\n }\n int mid = start + (end - start) / 2;\n ListNode* left = mergeKListsHelper(lists, start, mid);\n ListNode* right = mergeKListsHelper(lists, mid + 1, end);\n return merge(left, right);\n }\n \n ListNode* merge(ListNode* l1, ListNode* l2) {\n ListNode* dummy = new ListNode(0);\n ListNode* curr = dummy;\n \n while (l1 && l2) {\n if (l1->val < l2->val) {\n curr->next = l1;\n l1 = l1->next;\n } else {\n curr->next = l2;\n l2 = l2->next;\n }\n curr = curr->next;\n }\n \n curr->next = l1 ? l1 : l2;\n \n return dummy->next;\n }\n};\n\n```\n![8873f9b1-dfa4-4d9c-bb67-1b6db9d65e35_1674992431.3815322.jpeg]()\n\n
2,202
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
11,861
103
# Video Solution\n\n\n# Approach & Complete Inutuition\nMethod 1: Brute Force\nMethod 2: Compare K elements One By One\nMethod 3: Compare K elements by Priority Queue\nMethod 4: Merge 2 Lists at a time\nMethod 5: Merge K lists by Divide & Conquer (**`Most Optimal`**)\n\n# Image Explanation\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n![image.png]()\n\n\n# Method 5 - Code (Divide & Conquer)\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* mergeKLists(vector<ListNode*>& lists) {\n if(lists.size() == 0) return NULL;\n return mergeKListsHelper(lists, 0, lists.size()-1);\n }\n\n ListNode* mergeKListsHelper(vector<ListNode*>& lists, int start, int end) {\n if(start>end) return NULL; \n if(start==end) return lists[start];\n\n int mid = start + (end-start)/2;\n ListNode* left = mergeKListsHelper(lists, start, mid);\n ListNode* right = mergeKListsHelper(lists, mid + 1, end);\n return merge(left, right);\n }\n\n ListNode* merge(ListNode* list1Head, ListNode* list2Head) {\n ListNode* dummyHead = new ListNode(-1);\n ListNode* dummyTail = dummyHead;\n\n while(list1Head!=NULL && list2Head!=NULL){\n if(list1Head->val < list2Head->val){\n dummyTail->next = list1Head;\n list1Head = list1Head->next;\n }else{\n dummyTail->next = list2Head;\n list2Head = list2Head->next;\n }\n dummyTail = dummyTail->next;\n }\n dummyTail->next = (list1Head != NULL) ? list1Head : list2Head;\n return dummyHead->next;\n }\n};\n```\n\n# Method 3 - Code (Priority Queue)\n```\nclass Solution {\npublic:\n ListNode* mergeKLists(vector<ListNode*>& lists) {\n if(lists.size() == 0) return NULL;\n\n ListNode* dummyHead = new ListNode(-1);\n ListNode* dummyTail = dummyHead;\n\n priority_queue<pair<int, ListNode*>, vector<pair<int, ListNode*>>, greater<pair<int, ListNode*>>> pq;\n for(auto head : lists) if(head != NULL) pq.push({head->val, head});\n\n while(!pq.empty()){\n ListNode* minNode = pq.top().second;\n pq.pop();\n if(minNode->next != NULL) pq.push({minNode->next->val, minNode->next});\n\n dummyTail->next = minNode;\n dummyTail = dummyTail->next;\n }\n return dummyHead->next;\n }\n};\n```
2,204
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
2,003
5
# Complexity\n- Time complexity:\nO(NlogK), where K is the number of Sorted Lists/lists.size(), since at a time *atmost* K elements in MinHeap or OrderedSet\n\n- Space complexity:\nO(N)\n\n# Using Min_Heap\n```\nclass Solution {\npublic:\n ListNode* mergeKLists(vector<ListNode*>&lists) \n {\n //instead of checking everytime k lists and appending minimum of all to our answer list, maintain priority queue which gives us the minimum element in O(1) instead of O(K), where K is number of lists.\n //Sure O(logN) time would be required to insert and delete but its far off better than linear time\n priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>minheap;//value,index of ListNode in vector\n for(int i=0;i<lists.size();i++)\n {\n if(lists[i]!=NULL)\n {\n minheap.push({lists[i]->val,i});\n }\n }\n if(minheap.empty())//Edge Case Handling\n {\n return NULL;\n }\n ListNode* node=new ListNode();\n ListNode* head=node;//store the head of ans\n while(1)\n {\n pair<int,int>x=minheap.top();\n minheap.pop();\n node->val=x.first;\n if(lists[x.second]->next!=NULL)//check if end of list not reached\n {\n lists[x.second]=lists[x.second]->next;//traverse list further\n minheap.push({lists[x.second]->val,x.second});//push value of current pointer at this list\n }\n if(!minheap.empty())//still elements exist to insert in list\n {\n node->next=new ListNode();\n node=node->next;\n }\n else//all elements inserted and lists traversed\n {\n break;\n }\n }\n return head;\n }\n};\n```\n# Using Ordered_Set\n```\nclass Solution {\npublic:\n ListNode* mergeKLists(vector<ListNode*>&lists) \n {\n //same concept of pair as before\n set<pair<int,int>>listmin;\n for(int i=0;i<lists.size();i++)\n {\n if(lists[i]!=NULL)\n {\n listmin.insert({lists[i]->val,i});\n }\n }\n if(listmin.empty())\n {\n return NULL;\n }\n ListNode* node=new ListNode();\n ListNode* head=node;\n while(1)\n {\n pair<int,int>x=*(listmin.begin());\n listmin.erase(listmin.begin());\n node->val=x.first;\n if(lists[x.second]->next!=NULL)\n {\n lists[x.second]=lists[x.second]->next;\n listmin.insert({lists[x.second]->val,x.second});\n }\n if(!listmin.empty())\n {\n node->next=new ListNode();\n node=node->next;\n }\n else\n {\n break;\n }\n }\n return head;\n }\n};\n```\n
2,206
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
1,598
5
```\nclass Solution {\npublic:\n ListNode* mergeKLists(vector<ListNode*>& lists) {\n map<int, int> mp;\n for(auto& ln : lists){\n while(ln){\n mp[ln->val]++;\n ln = ln->next;\n }\n }\n if(!mp.size()) return nullptr;\n ListNode* ans = new ListNode();\n ListNode* p = ans;\n for(auto& v: mp){\n for(int i{}; i<v.second; i++){\n p->next = new ListNode(v.first);\n p = p->next;\n }\n \n }\n return ans->next;\n }\n};\n```
2,209
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
788
5
\n[see the Successfully Accepted Submission]()\n```Python\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n\nclass Solution(object):\n def mergeKLists(self, lists):\n # Create a new ListNode representing the head of the merged list.\n # Initialize it with an empty ListNode.\n newList = ListNode()\n # Create a temporary ListNode to build the merged list.\n temporary_list = newList\n\n # Define a helper function to get the smallest value among the current heads of all lists.\n def getSmallestValue():\n min_value = float(\'inf\') # Initialize the minimum value as positive infinity.\n min_index = -1 # Initialize the index of the list with the minimum value as -1.\n for i in range(len(lists)):\n # Check if the current list is not empty and its head value is smaller than the current minimum value.\n if lists[i] is not None and lists[i].val < min_value:\n min_value = lists[i].val\n min_index = i\n if min_index != -1:\n # If a list with the minimum value is found, move its head to the next element.\n lists[min_index] = lists[min_index].next\n return min_value\n \n # Loop to merge the lists.\n while True:\n x = getSmallestValue() # Get the smallest value among the current heads of lists.\n if x == float(\'inf\'):\n # If the smallest value is still positive infinity, all lists are empty, so break the loop.\n break\n # Create a new ListNode with the value of the smallest element.\n c = ListNode(val=x)\n # Connect the new node to the merged list.\n temporary_list.next = c\n temporary_list = temporary_list.next # Move the temporary list pointer forward.\n \n # Return the merged list, excluding the initial empty ListNode.\n return newList.next\n\n```\n\n![image]()\n\n\nPython | Easy | Heap | \n\n\n
2,210
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
8,361
65
**NOTE 1 - PLEASE READ INTUITION AND APPROACH FIRST THEN SEE THE CODE. YOU WILL DEFINITELY UNDERSTAND THE CODE LINE BY LINE AFTER SEEING THE APPROACH.**\n\n**NOTE 2 - BEFORE SOLVING THIS PROBELM, I WILL HIGHLY RECOMMEND YOU TO SOLVE BELOW PROBLEM FOR BETTER UNDERSTANDING.**\n**21. Merge Two Sorted Lists :** \n**SOLUTION :** \n\n# Intuition of this Problem:\n**This solution uses the merge sort algorithm to merge all the linked lists in the input vector into a single sorted linked list. The merge sort algorithm works by recursively dividing the input into halves, sorting each half separately, and then merging the two sorted halves into a single sorted output.**\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach for this Problem:\n1. Define a function merge that takes two pointers to linked lists as input and merges them in a sorted manner.\n - a. Create a dummy node with a value of -1 and a temporary node pointing to it.\n - b. Compare the first node of the left and right linked lists, and append the smaller one to the temporary node.\n - c. Continue this process until either of the lists becomes empty.\n - d. Append the remaining nodes of the non-empty list to the temporary node.\n - e. Return the next node of the dummy node.\n\n1. Define a function mergeSort that takes three arguments - a vector of linked lists, a starting index, and an ending index. It performs merge sort on the linked lists from the starting index to the ending index.\n - a. If the starting index is equal to the ending index, return the linked list at that index.\n - b. Calculate the mid index and call mergeSort recursively on the left and right halves of the vector.\n - c. Merge the two sorted linked lists obtained from the recursive calls using the merge function and return the result.\n\n1. Define the main function mergeKLists that takes the vector of linked lists as input and returns a single sorted linked list.\n - a. If the input vector is empty, return a null pointer.\n - b. Call the mergeSort function on the entire input vector, from index 0 to index k-1, where k is the size of the input vector.\n - c. Return the merged linked list obtained from the mergeSort function call.\n1. End of algorithm.\n<!-- Describe your approach to solving the problem. -->\n\n# Humble Request:\n- If my solution is helpful to you then please **UPVOTE** my solution, your **UPVOTE** motivates me to post such kind of solution.\n- Please let me know in comments if there is need to do any improvement in my approach, code....anything.\n- **Let\'s connect on** \n\n![57jfh9.jpg]()\n\n# Code:\n```C++ []\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* merge(ListNode *left, ListNode *right) {\n ListNode *dummy = new ListNode(-1);\n ListNode *temp = dummy;\n while (left != nullptr && right != nullptr) {\n if (left -> val < right -> val) {\n temp -> next = left;\n temp = temp -> next;\n left = left -> next;\n }\n else {\n temp -> next = right;\n temp = temp -> next;\n right = right -> next;\n }\n }\n while (left != nullptr) {\n temp -> next = left;\n temp = temp -> next;\n left = left -> next;\n }\n while (right != nullptr) {\n temp -> next = right;\n temp = temp -> next;\n right = right -> next;\n }\n return dummy -> next;\n }\n ListNode* mergeSort(vector<ListNode*>& lists, int start, int end) {\n if (start == end) \n return lists[start];\n int mid = start + (end - start) / 2;\n ListNode *left = mergeSort(lists, start, mid);\n ListNode *right = mergeSort(lists, mid + 1, end);\n return merge(left, right);\n }\n ListNode* mergeKLists(vector<ListNode*>& lists) {\n if (lists.size() == 0)\n return nullptr;\n return mergeSort(lists, 0, lists.size() - 1);\n }\n};\n```\n```Java []\nclass Solution {\n public ListNode merge(ListNode left, ListNode right) {\n ListNode dummy = new ListNode(-1);\n ListNode temp = dummy;\n while (left != null && right != null) {\n if (left.val < right.val) {\n temp.next = left;\n temp = temp.next;\n left = left.next;\n } else {\n temp.next = right;\n temp = temp.next;\n right = right.next;\n }\n }\n while (left != null) {\n temp.next = left;\n temp = temp.next;\n left = left.next;\n }\n while (right != null) {\n temp.next = right;\n temp = temp.next;\n right = right.next;\n }\n return dummy.next;\n }\n \n public ListNode mergeSort(List<ListNode> lists, int start, int end) {\n if (start == end) {\n return lists.get(start);\n }\n int mid = start + (end - start) / 2;\n ListNode left = mergeSort(lists, start, mid);\n ListNode right = mergeSort(lists, mid + 1, end);\n return merge(left, right);\n }\n \n public ListNode mergeKLists(List<ListNode> lists) {\n if (lists.size() == 0) {\n return null;\n }\n return mergeSort(lists, 0, lists.size() - 1);\n }\n}\n\n```\n```Python []\nclass Solution:\n def merge(self, left: ListNode, right: ListNode) -> ListNode:\n dummy = ListNode(-1)\n temp = dummy\n while left and right:\n if left.val < right.val:\n temp.next = left\n temp = temp.next\n left = left.next\n else:\n temp.next = right\n temp = temp.next\n right = right.next\n while left:\n temp.next = left\n temp = temp.next\n left = left.next\n while right:\n temp.next = right\n temp = temp.next\n right = right.next\n return dummy.next\n \n def mergeSort(self, lists: List[ListNode], start: int, end: int) -> ListNode:\n if start == end:\n return lists[start]\n mid = start + (end - start) // 2\n left = self.mergeSort(lists, start, mid)\n right = self.mergeSort(lists, mid + 1, end)\n return self.merge(left, right)\n \n def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n if not lists:\n return None\n return self.mergeSort(lists, 0, len(lists) - 1)\n\n```\n\n# Time Complexity and Space Complexity:\n- Time complexity: **O(N log k)**, where N is the total number of nodes in all the linked lists, and k is the number of linked lists in the input vector. This is because the merge sort algorithm requires O(N log N) time to sort N items, and in this case, N is the total number of nodes in all the linked lists. The number of levels in the recursion tree of the merge sort algorithm is log k, where k is the number of linked lists in the input vector. Each level of the recursion tree requires O(N) time to merge the sorted lists, so the total time complexity is O(N log k).\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: **O(log k)**, which is the maximum depth of the recursion tree of the merge sort algorithm. The space used by each recursive call is constant, so the total space used by the algorithm is proportional to the maximum depth of the recursion tree. Since the depth of the tree is log k, the space complexity of the algorithm is O(log k).\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->
2,211
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
265,396
727
If someone understand how priority queue works, then it would be trivial to walk through the codes. \n\nMy question: is that possible to solve this question under the same time complexity without implementing the priority queue?\n\n\n public class Solution {\n public ListNode mergeKLists(List<ListNode> lists) {\n if (lists==null||lists.size()==0) return null;\n \n PriorityQueue<ListNode> queue= new PriorityQueue<ListNode>(lists.size(),new Comparator<ListNode>(){\n @Override\n public int compare(ListNode o1,ListNode o2){\n if (o1.val<o2.val)\n return -1;\n else if (o1.val==o2.val)\n return 0;\n else \n return 1;\n }\n });\n \n ListNode dummy = new ListNode(0);\n ListNode tail=dummy;\n \n for (ListNode node:lists)\n if (node!=null)\n queue.add(node);\n \n while (!queue.isEmpty()){\n tail.next=queue.poll();\n tail=tail.next;\n \n if (tail.next!=null)\n queue.add(tail.next);\n }\n return dummy.next;\n }\n }
2,212
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
8,993
154
***Brief note about Question-***\n\nWe have to ***Merge all the linked-lists into one sorted linked-list and return it.***\n```\nTake an example -\nGiven: k number of sorted linked list in ascending order.\nAim: Merge them into a single sorted linked list.\n\nTake anthor example which is not given in question-\nL1: 1 -> 5 -> 7 -> 9 -> N\nL2: 2 -> 4 -> 8 -> N\nL3: 3 -> 6 -> N\n\nSo our answer should like this:\n1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> N\n```\n________________________\n***Solution - I (Most basic approach, Accepted)-***\n* Okay, so the most basic approach we can think of is, we are obedient person, and not to do anything extra from ourself,\n* We will simply do what the question wants us to do, we create an array which store all the elements of all \'k\' linked list present in the array.\n* After storing all elements, we sort them a/c to their vaules.\n* Now, the only task which is left is to link them, so we start linking them.\n\n**Okay, I got the approach, but how i will implement this or code these words-**\n\n1. We take help of a `vector pair` which of value and Node type.\n1. But why vector pair?\n1. See, *Here we have k different linked list na and each linked list contain some elements so to observe that we need a vector pair.*\n1. Okay good, I take a vector pair,so now what i have to do?\n1. Now we start storing each value in this vector pair.\n1. After this, by using `sort function` (present in STL) we sort this vectorAnd at last, i start linking them, it can be done simply by putting next pointer i.e `arr[i].second -> next = arr[i + 1].second`.\n\n```\nSuppose if total number of nodes present in all linked list is \'n\' \nTime Complexity --> O(n log n) // as sorting takes (n log n) time\nSpace Complexity --> O(n) // to store nodes of the all linked list\nIt paases [ 133 / 133] in built test cases\n```\n**Code (C++)**\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* mergeKLists(vector<ListNode*>& lists) {\n int k = lists.size(); // taking size of the list\n if(k == 0) // if size is zero\n return NULL; // simply return NULL\n \n // making a vector pair where first contain value and second contain node\n vector<pair<int, ListNode*>> arr; \n \n for(int i = 0; i < k; i++) // traverse all over the list\n {\n ListNode* curr_list = lists[i]; // extracting current linked list\n \n while(curr_list != NULL) // while current linked list is NOT NULL\n {\n arr.push_back({curr_list -> val, curr_list}); // push into vector\n curr_list = curr_list -> next;\n }\n }\n \n // this does not gurantee that k is zero, \n // suppose an array like this [[],[],[],],here k = 3 and size of array is 0\n if(arr.size() == 0) // if their is no element i.e zero element\n return NULL;\n \n sort(arr.begin(), arr.end()); // sort the vector on the basis of values\n \n // start making links b/w the elements of vector\n for(int i = 0; i < arr.size() - 1; i++)\n {\n arr[i].second -> next = arr[i + 1].second;\n }\n \n // in the next of last node put NULL\n arr[arr.size() - 1].second -> next = NULL;\n \n return arr[0].second; // return first node of the vector\n }\n};\n```\n___________________________\n***Solution - II (Further optimization in time as well as in space, Using priority queue, Accepted)-***\n* Now, we want to become a good programmer and anyhow we want to optimize our soloution.\n* The main point is to observe here is that ***every linked list is already sorted*** and our task is just to merge them.\n* Our approach to merge linked list is same as about merge function of merge sort.\n* In merge sort, we have just two arrays / linked list but here we have \'k\' linked list.\n* So by using `min heap` we compare k node values and add the smallest one to the final list.\n* One property of min heap we have to remember here is that, ***it keeps smallest element always on the top,*** so using that property we merge our k sorted linked list.\n```\nSuppose if total number of nodes present in all linked list is \'n\' \nTime Complexity --> O(n log k) // as we are using min heap\nSpace Complexity --> O(k) // at a single point of time min heap always handle the k elements\nIt paases [ 133 / 133] in built test cases\n```\n**Code (C++)**\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\n\n\nclass Solution {\npublic:\n // we define pair as pi\n #define pi pair<int, ListNode* >\n \n ListNode* mergeKLists(vector<ListNode*>& lists) {\n int k = lists.size(); // taking the size of the linked list\n \n if(k == 0) // if no linked list is present\n return NULL; // simply return null\n \n priority_queue<pi, vector<pi>, greater<pi>> minh; // making priority queue\n \n for(int i = 0; i < k; i++) // traverse from the whole array \n {\n ListNode* curr_list = lists[i]; // extracting current linked list\n \n if(curr_list != NULL) // if element present in the linked list\n {\n minh.push({curr_list -> val, curr_list}); // push into min heap\n }\n }\n \n // this does not gurantee that k is zero, \n // suppose an array like this [[],[],[],],here k = 3 and size of array is 0\n if(minh.size() == 0) // if their is no element i.e zero element\n return NULL;\n \n ListNode* head = new ListNode(); // can also be called as dummy\n ListNode* curr = head; // make a pointer pointing to head\n \n while(minh.empty() == false) // adding further most elements to min heap\n {\n pair<int, ListNode*> temp = minh.top(); // extracting top pair\n minh.pop(); // pop that pair\n \n if(temp.second -> next != NULL) // if elements still remaining in the linked list then push them\n {\n minh.push({temp.second -> next -> val, temp.second -> next});\n }\n \n curr -> next = temp.second;\n curr = curr -> next;\n }\n \n curr -> next = NULL; \n head = head -> next; // move head, which is actually containg the list\n \n return head; // return head\n }\n};\n```\n___________________________\n***Solution - III (Further optimization in space, Accepted)-***\n* Okay, the question arises, if we just have to merge k linked list, \n* Is the use of priority queue is necesssary? Can\'t we do it without using the priority queue?\n* The answer is ***YES***, we can do further optimization in space complexity as well.\n* We use `two pointers` for doing this.\n* First we put start pointer to zero index and last pointer to last index and after that we start merging them thinking of as two sorted linked list.\n* And again we will continue this task until we get a single linked list.\n* See commented code, you will get it easily.\n```\nSuppose if total number of nodes present in all linked list is \'n\' \nTime Complexity --> O(n log k)\nSpace Complexity --> O(1) \nIt paases [ 133 / 133] in built test cases\n```\n**Code (C++)**\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n // this do the same work as merge function of merging two values\n ListNode* merge(ListNode* first, ListNode* second)\n {\n ListNode* result = NULL;\n \n if(first == nullptr)\n return second;\n \n if(second == nullptr)\n return first;\n \n \n if(first -> val <= second -> val)\n {\n result = first;\n result -> next = merge(first -> next, second);\n }\n else\n {\n result = second;\n result -> next = merge(first, second -> next);\n }\n return result;\n }\n ListNode* mergeKLists(vector<ListNode*>& arr) {\n int k = arr.size(); // extracting size of array\n if(k == 0) // if size of array is value\n return NULL;\n \n int start = 0; // start pointer\n int last = k -1; // last pointer\n int temp;\n while(last != 0) // if last pointer not becomes zero\n {\n start = 0;\n temp = last;\n while(start < temp)\n {\n // merge them and store in one of the linked list\n arr[start] = merge(arr[start],arr[temp]);\n start++; // increment start\n temp--; // decrese start\n \n if(start >= temp) // if at any point start passes the temp\n {\n last = temp;\n }\n }\n }\n return arr[0]; // return first linked list of the aray as now it contains the all nodes in the sorted order.\n \n }\n};\n```\n\n***`If u find this useful , please consider to give a upvote!!`***
2,213
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
110,423
596
ListNode *mergeKLists(vector<ListNode *> &lists) {\n if(lists.empty()){\n return nullptr;\n }\n while(lists.size() > 1){\n lists.push_back(mergeTwoLists(lists[0], lists[1]));\n lists.erase(lists.begin());\n lists.erase(lists.begin());\n }\n return lists.front();\n }\n ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {\n if(l1 == nullptr){\n return l2;\n }\n if(l2 == nullptr){\n return l1;\n }\n if(l1->val <= l2->val){\n l1->next = mergeTwoLists(l1->next, l2);\n return l1;\n }\n else{\n l2->next = mergeTwoLists(l1, l2->next);\n return l2;\n }\n }\n\nThe second function is from Merge Two Sorted Lists. \n\nThe basic idea is really simple. We can merge first two lists and then push it back. Keep doing this until there is only one list left in vector. Actually, we can regard this as an iterative divide-and-conquer solution.
2,218
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
2,539
6
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n\n int length(ListNode* h){\n ListNode* l=h;\n int c=0;\n while(l){\n c+=1;\n l=l->next;\n }\n return c;\n }\n\n ListNode* merge(ListNode* l1,ListNode* l2){\n ListNode* h1=l1,*h2=l2;\n ListNode* ll=new ListNode(0);\n ListNode* ans=ll;\n while(h1 and h2){\n if(h1->val <=h2->val){\n ans->next=h1;\n h1=h1->next;\n } else{\n ans->next=h2;\n h2=h2->next;\n }\n ans=ans->next;\n }\n\n if(h1)\n ans->next=h1;\n if(h2)\n ans->next=h2;\n\n return ll->next;\n \n }\n\n ListNode* mergeKLists(vector<ListNode*>& a) {\n ListNode* st,temp;\n if(a.size()==0)\n return NULL;\n ListNode* l1=a[0];\n for(int i=1;i<a.size();i+=1){\n \n ListNode* l2=a[i];\n if(length(l1)<length(l2)){\n l1=merge(l2,l1);\n } else\n l1=merge(l1,l2);\n\n }\n return l1;\n \n \n }\n};\n```
2,219
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
921
6
```\nclass Solution {\npublic:\n ListNode* merge(ListNode* head1,ListNode* head2){\n ListNode* head=NULL;\n ListNode* tail=NULL;\n while(head1&&head2){\n if(head1->val<=head2->val){\n if(!head){\n head=head1;\n tail=head;\n }\n else{\n tail->next=head1;\n tail=tail->next;\n }\n head1=head1->next;\n }\n else{\n if(!head){\n head=head2;\n tail=head;\n }\n else{\n tail->next=head2;\n tail=tail->next;\n }\n head2=head2->next;\n }\n }\n while(head1){\n if(!head){\n head=head1;\n tail=head;\n }\n else{\n tail->next=head1;\n tail=tail->next;\n }\n head1=head1->next;\n }\n while(head2){\n if(!head){\n head=head2;\n tail=head;\n }\n else{\n tail->next=head2;\n tail=tail->next;\n }\n head2=head2->next; \n }\n return head;\n }\n ListNode* mergeKLists(vector<ListNode*>& lists) {\n int n=lists.size();\n if(lists.empty()) return NULL;\n ListNode* head=lists[0];\n for(int i=1;i<n;i++){\n head=merge(head,lists[i]);\n }\n return head;\n }\n};\n```
2,221
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
4,111
7
# Approach\nLet **pN - n\'th pointer**\n1. lists = [p1, p2, p3, p4, p5, p6, p7]\n2. lists = [p1, null, p3, null, p5, null, p7]\nmerge lists[i] with lists[i + 1] and save in lists[i]\nand set counter **cnt** that will be actual positions iterator.\nWe just swap lists[i] and lists[cnt] every iteration **swap(lists[i])**.\nIf there was odd number of lists, then just leave it,\nwe will merge it when there will be even number of elements in lists.\n2. [p1, p3, p5, p7, null, null, null]\n**cnt = 3, lists[cnt] = p7.**\nActually we dont need to set nullptr to trash elements (lists[i], where i is odd), i wrote null just for explanation.\n2. [p1, null, p5, null, null, null, null]\n3. [p1, p5, null, null, null, null, null]\n4. [p1, null, null, null, null, null, null]\n**So p1 is answer.**\n\n# Complexity\n- Time complexity:\nO(n*log(k))\nn - lists number, k - max nodes in list\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n // O(nlogk) - time complexity\n // O(1) - memory complexity\n ListNode* mergeKLists(std::vector<ListNode*>& lists) {\n int n = static_cast<int>(lists.size());\n if (!n || n == 1 && lists.front() == nullptr) return nullptr;\n ListNode* last = nullptr;\n while(n > 1) {\n int cnt = 0;\n for(int i = 0; i < n - 1; i+=2) {\n lists[i] = merge2Lists(lists[i], lists[i + 1]);\n swap(lists[i], lists[cnt]);\n ++cnt;\n }\n swap(lists[n-1], lists[cnt]);\n n = n/2 + n%2;\n }\n return lists.front();\n }\n\n ListNode* merge2Lists(ListNode* l1, ListNode* l2) {\n start = nullptr;\n if (l1 && l2) {\n if (l1->val < l2->val) {\n start = l1;\n l1 = l1->next;\n } else {\n start = l2;\n l2 = l2->next;\n }\n } else if (l1) { return l1; }\n else if (l2) { return l2; }\n else return nullptr;\n ListNode* cur = start;\n while(true) {\n if (l1 && l2) {\n if (l1->val < l2->val) {\n cur->next = l1;\n cur = cur->next;\n l1 = l1->next;\n } else {\n cur->next = l2;\n cur = cur->next;\n l2 = l2->next;\n }\n } else if (l1) {\n cur->next = l1;\n break;\n } else if (l2) {\n cur->next = l2;\n break;\n } else break;\n }\n return start;\n }\n ListNode* start = nullptr;\n};\n```
2,227
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
12,374
237
Reference: [LeetCode]() <span class="gray">EPI 10.1</span>\nDifficulty: <span class="red">Hard</span>\n\n\n## Problem\n\n> Merge `k` sorted linked lists and return it as one sorted list. Analyze and describe its complexity.\n\n**Example:** \n\n```java\nInput:\n[\n 1->4->5,\n 1->3->4,\n 2->6\n]\nOutput: 1->1->2->3->4->4->5->6\n```\n\n\n## Analysis\n\n**Focus on the third and fifth solution.**\n\n**Test Case:**\n\n```java\n// 1\n[[1,4,5],[1,3,4],[2,6]]\n[1,2,4,4,5]\n// 2\n[[], [], []]\n[]\n// 3\n[[1,2],[],[5]]\n[1,2,5]\n// 4\n[[1,4,5],[2,4]]\n[1,2,4,4,5]\n// 5\n[[1]]\n[1]\n// 6 ---- Be careful of this one\n[]\n```\n\n### Brute-Force\n\nIt is okay if `N` is not too large.\n\n- Traverse all the linked lists and collect the values of the nodes into an `array`. - `O(N)`\n- Sort the array. - `O(N\\log{N})`\n- Traverse the array and make the linked list. - `O(N)`\n\n**Time:** `O(N\\log{N})` where `N` is the total number of nodes.\n**Space:** `O(N)` since we need an array and a new linked list.\n\n\n\n\n### Compare One-By-One\n\n(if `k` is much less than `N`, `k` is the number of lists)\n\nCompare every `k` nodes (head of every list) and get the smallest node.\n\n**Note:**\n\n- Use `minIdx` to record the location and to check if the list is empty.\n\n```java\npublic ListNode mergeKLists(ListNode[] lists) {\n if (lists == null || lists.length == 0) {\n return null;\n }\n ListNode dummy = new ListNode(-1);\n ListNode prev = dummy;\n\n while (true) {\n ListNode minNode = null;\n int minIdx = -1;\n \n // Iterate over lists\n for (int i = 0; i < lists.length; ++i) {\n ListNode currList = lists[i];\n if (currList == null) continue;\n if (minNode == null || currList.val < minNode.val) {\n minNode = currList;\n minIdx = i;\n }\n }\n // check if finished\n if (minNode == null) break;\n\n // link\n prev.next = minNode;\n prev = prev.next;\n\n // delete\n lists[minIdx] = minNode.next; // may be null\n }\n return dummy.next;\n}\n```\n\n\n**Time:** `O(kN)` where `k` is the number of linked lists. `311 ms`\n**Space:** `O(N)` creating a new linked list. Or `O(1)` if we apply an in-place method. Connect selected nodes instead of creating new nodes.\n\n\n\n### Compare One-By-One (minPQ)\n\nUse a minimum `priority queue` to store `k` nodes. Pop the smallest node and offer its next node if it is not `null`.\n\n```java\n// Compare One-By-One (PQ)\npublic ListNode mergeKLists(ListNode[] lists) {\n if (lists == null || lists.length == 0) {\n return null;\n }\n ListNode dummy = new ListNode(-1);\n ListNode prev = dummy;\n\n PriorityQueue<ListNode> minPQ = new PriorityQueue<>((o1, o2) -> {\n return o1.val - o2.val;\n });\n\n // Init PQ\n for (int i = 0; i < lists.length; ++i) {\n if (lists[i] != null) {\n minPQ.offer(lists[i]);\n }\n }\n\n // Play with PQ\n while (minPQ.size() > 0) {\n ListNode curr = pq.poll();\n prev.next = curr;\n prev = prev.next; // update\n\n // you don\'t need to set curr.next as null since the last node is always be one of the last node of each list. Its next must be null.\n if (curr.next != null) {\n minPQ.offer(curr.next);\n }\n }\n \n return dummy.next;\n}\n```\n\n**Time:** `O(N\\log{k})` `34 ms`\n- Initializing the priority queue takes `O(k\\log{k})`\n- Pop `N` nodes from the priority queue takes `O(N\\log{k})`\n\n**Space:** `O(k)` since priority queue stores `k` nodes. `O(1)` or `O(N)` depends on the input `N` and `k` and whether we create a new linked list.\n\n\n\n### Merge Lists One-By-One\n\nWe need to merge `k` lists by merging `(k-1)` times.\n\n**Note:**\n\n- `mergeList(dummy.next, n)` is thoughtful. At the beginning, `dummy.next` is null, but it does not matter.\n- Alternatively, we can use the first place of the array to store merged list.\n\n```java\npublic ListNode mergeKLists(ListNode[] lists) {\n if (lists == null || lists.length == 0) {\n return null;\n }\n // Use the 0-th list as a return list\n for (int i = 1; i < lists.length; ++i) {\n lists[0] = mergeList(lists[0], lists[i]);\n }\n\n return lists[0];\n}\n\nprivate ListNode mergeList(ListNode n1, ListNode n2) {\n ListNode dummy = new ListNode(-1);\n ListNode prev = dummy;\n while (n1 != null && n2 != null) {\n if (n1.val < n2.val) {\n prev.next = n1;\n n1 = n1.next;\n } else {\n prev.next = n2;\n n2 = n2.next;\n }\n prev = prev.next;\n }\n prev.next = (n1 != null) ? n1 : n2;\n\n return dummy.next;\n}\n```\n\n\n**Time:** `O(kN)` `250 ms`\n- Merge two sorted lists in `O(n)` time where `n` is the total number of nodes in two lists. (worst case)\n- To sum up we have: `O(\\sum_{i=1}^{k-1}(i * \\frac{N}{k} + \\frac{N}{k}) = O(kN)`. (key: `n = \\frac{N}{k}`) `skip it...`\n\n**Space:** `O(1)` since we merge in place.\n\n\n\n\n### Merge Lists with Divide And Conquer\n\nIn effect, we don\'t need to traverse most nodes many times repeatedly. We can divide lists in half until there is only one list. Merge them one by one to get the final result. It\'s similar to mergesort.\n\n\n**Note:**\n\n- Recall of the `left-leaning` and `right-leaning` cases.\n- The base case is thoughtful. `lo > hi` actually won\'t occur. And `lists[lo]` won\'t change other elements on the other side.\n- `lists.length == 0` condition is very important.\n - Input case: `[]`.\n\n```java\n// mergeDivideAndConquer - O(kN)\npublic ListNode mergeDivideAndConquer(ListNode[] lists) {\n if (lists == null || lists.length == 0) {\n return null;\n }\n return divideAndConquer(lists, 0, lists.length - 1);\n}\n\nprivate ListNode divideAndConquer(ListNode[] lists, int lo, int hi) {\n if (lo > hi) { // invalid\n return null;\n }\n if (lo == hi) { // size = 1\n return lists[lo];\n }\n int mid = lo + (hi - lo) / 2; // left-leaning\n ListNode left = divideAndConquer(lists, lo, mid);\n ListNode right = divideAndConquer(lists, mid + 1, hi);\n return mergeList(left, right);\n}\n\nprivate ListNode mergeList(ListNode n1, ListNode n2) { ... }\n```\n\n\n**Time:** `O(N\\log{k})` `2 ms`\n**Space:** `O(\\log{k})` if we use recursion (depth of the recursion tree).\n \n![]( "Merge with Divide And Conquer")\n\n\n
2,228
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
1,655
13
**Similar to merge sort (Divide and conquer)**\n```\nclass Solution {\n public ListNode mergeKLists(ListNode[] lists) {\n if (lists == null || lists.length == 0) {\n return null;\n }\n return divideAndConquer(lists, 0, lists.length - 1);\n }\n public ListNode divideAndConquer(ListNode[] lists,int low,int high){\n if(low>high)\n return null;\n if(low==high)\n return lists[low];\n int mid=low+(high-low)/2;\n ListNode left=divideAndConquer(lists,low,mid);\n ListNode right=divideAndConquer(lists,mid+1,high);\n return merge(left,right);\n }\n public ListNode merge(ListNode n1, ListNode n2) {\n ListNode dummy = new ListNode(-1);\n ListNode prev = dummy;\n while (n1!=null && n2!=null){\n if (n1.val<n2.val) {\n prev.next = n1;\n n1 = n1.next;\n }\n else{\n prev.next = n2;\n n2 = n2.next;\n }\n prev = prev.next;\n }\n if(n1!=null)\n prev.next=n1;\n if(n2!=null)\n prev.next=n2;\n return dummy.next;\n }\n}\n```\n**Time Complexity: O(Nlog(k))\nSpace Complexity: O(log(k)) as we use recursion (depth of the recursion tree)**\n\n![image]()\n\n![image]()\n
2,230
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
1,394
7
# Intuition\nSince the constraints were:\n* length of lists, $$k = 10^4$$\n* length of each linked lists say $$n = 500$$\n \nIt was not a difficult choice to go for time complexity of $$O(kn)$$ \n\nAs we will get a TLE in python (generally) if we try to exceed $$O(10^8)$$.\nBut our solution takes $$O(10^4 * 500) < O(10^8)$$\n\n\n\n# Approach\n1. We will iterate through the lists and use the first element of each linked list to find the minimum among them, which will take $$O(k)$$ as length of list is $$k$$.\n2. We will follow step 1 till all the linked lists are completely explored. We will be able to do it in $$O(n)$$ time as length of any listed list is upper bounded by $$n$$.\n\n# Complexity\n- Time complexity: $$O(kn)$$ as both step 1 and step 2 are performed simultaneously.\n\n- Space complexity: $$O(n)$$ to create a new linked list whose length is upper bounded by n.\n\n# Code\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n\nclass Solution:\n def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n \n l = ListNode() # the new list that we want to return\n t = l # taking a temporary copy of the new list as we need to move to next pointers to store data.\n\n # get the minimum front value of all linked lists in the input list.\n def get_min():\n min_val, min_indx = float(\'inf\'), -1\n for i in range(len(lists)):\n if lists[i] != None and lists[i].val < min_val:\n min_val = lists[i].val\n min_indx = i\n if min_indx != -1:\n # when a min value is found, \n # increment the linked list \n # so that we don\'t consider the same min value the next time \n # and also the next value of linked list comes at the front\n lists[min_indx] = lists[min_indx].next\n return min_val\n \n while(1):\n x = get_min() # get the mim value to add to new list\n if (x == float(\'inf\')): \n # if min value is not obtained that means all the linked lists are traversed so break\n break\n c = ListNode(val=x)\n t.next = c\n t = t.next\n return l.next # as we made l to be just a head for our actual linked list\n \n\n\n\n\n \n\n\n```
2,232
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
7,593
33
# Please UPVOTE\uD83D\uDE0A\n![image.png]()\n\n\n# Python3\n```\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:\n v=[]\n for i in lists:\n x=i\n while x:\n v+=[x.val]\n x=x.next\n v=sorted(v,reverse=True)\n ans=None\n for i in v:\n ans=ListNode(i,ans)\n return ans\n```\n# C++\n```\nclass Solution {\npublic:\n ListNode* mergeKLists(vector<ListNode*>& lists) {\n vector<int>v;\n for(int i=0;i<lists.size();i++){\n while(lists[i]){\n v.push_back(lists[i]->val);\n lists[i]=lists[i]->next;\n }\n }\n sort(rbegin(v),rend(v));\n ListNode* ans=nullptr;\n for(int i=0;i<v.size();i++){\n ans=new ListNode(v[i],ans);\n }\n return ans;\n }\n};\n```
2,234
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
95,937
420
public static ListNode mergeKLists(ListNode[] lists){\n return partion(lists,0,lists.length-1);\n }\n\n public static ListNode partion(ListNode[] lists,int s,int e){\n if(s==e) return lists[s];\n if(s<e){\n int q=(s+e)/2;\n ListNode l1=partion(lists,s,q);\n ListNode l2=partion(lists,q+1,e);\n return merge(l1,l2);\n }else\n return null;\n }\n\n //This function is from Merge Two Sorted Lists.\n public static ListNode merge(ListNode l1,ListNode l2){\n if(l1==null) return l2;\n if(l2==null) return l1;\n if(l1.val<l2.val){\n l1.next=merge(l1.next,l2);\n return l1;\n }else{\n l2.next=merge(l1,l2.next);\n return l2;\n }\n }
2,235
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
3,875
66
\u2714 ***All codes are running successfully !***\n*if you find that this post to be helpful for you, So, please take out **one second** for single UPVOTE.* \n\n----\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\n```\n\n----\n**Approach-1 : USING MIN HEAP**\n```\nclass Solution {\npublic:\n \n \n struct compare\n {\n bool operator()(ListNode* a, ListNode *b)\n {\n return a->val > b->val; // min heap \n }\n };\n \n ListNode* mergeKLists(vector<ListNode*>& arr) // saari linked list ka head arr mai hai\n {\n int j;\n for(j = 0;j< arr.size();j++){\n if(arr[j] != NULL)\n break;\n }\n if(j == arr.size()){ // all list empty\n return NULL;\n }\n \n priority_queue<ListNode*, vector<ListNode*>, compare>pq; \n for(int i = 0;i<arr.size();i++){\n if(arr[i] != NULL)\n pq.push(arr[i]);\n }\n \n ListNode *mergeH = new ListNode(0);\n ListNode *last = mergeH;\n while(!pq.empty())\n {\n ListNode* curr = pq.top();\n pq.pop();\n \n last->next = curr;\n last = last->next;\n \n if(curr != NULL && curr->next != NULL){\n pq.push(curr->next);\n }\n \n }\n return mergeH->next;\n }\n};\n```\n\n----\n**Approach - 2 : Using simple Merging of 2 sorted array**\n**Time : `381 ms`**\n```\nclass Solution {\npublic:\n \n ListNode* mergeTwoSorted(ListNode *a, ListNode* b)\n {\n if(a==NULL) return b;\n if(b==NULL) return a;\n \n if(a->val<=b->val){\n a->next = mergeTwoSorted(a->next, b);\n return a;\n }\n else{\n b->next = mergeTwoSorted(a, b->next);\n return b;\n }\n }\n \n ListNode* mergeKLists(vector<ListNode*>& lists)\n {\n if(lists.size()==0) return NULL;\n while(lists.size() > 1){\n lists.push_back(mergeTwoSorted(lists[0], lists[1])); // time consuming \n // erase first 2 heads of lists\n lists.erase(lists.begin()); // time consuming \n lists.erase(lists.begin());\n }\n return lists[0];\n }\n};\n```\n\n\n----\n**Approach - 3 : Optimization of Approach 2**\nwithout using **push_back**, **erase**, which is time consuming,\n**Time : `47 ms`**\n```\nclass Solution {\npublic:\n \n ListNode* mergeTwoSorted(ListNode *a, ListNode* b)\n {\n if(a==NULL) return b;\n if(b==NULL) return a;\n \n if(a->val<=b->val){\n a->next = mergeTwoSorted(a->next, b);\n return a;\n }\n else{\n b->next = mergeTwoSorted(a, b->next);\n return b;\n }\n }\n \n ListNode* mergeKLists(vector<ListNode*>& lists)\n {\n int n=lists.size();\n if(lists.size()==0) return NULL;\n while(n>1){\n \n for(int i=0;i<n/2;i++)\n lists[i] = mergeTwoSorted(lists[i], lists[n-i-1]);\n n = (n+1)/2;\n }\n return lists.front();\n }\n};\n```\n\n----\n**Approach - 4 : Iterative Merging of 2 lists**\n**Time :** **`17ms`**\n\n```\nclass Solution {\npublic:\n \n ListNode* mergeTwoSorted(ListNode *l1, ListNode* l2)\n {\n ListNode* dummy = new ListNode(-1);\n ListNode* last = dummy;\n \n while(l1 and l2)\n {\n if(l1->val <= l2->val){\n last->next = l1;\n last = l1;\n l1=l1->next;\n }\n else{\n last->next = l2;\n last = l2;\n l2=l2->next;\n }\n }\n \n if(!l1)\n last->next = l2;\n else\n last->next = l1;\n return dummy->next;\n }\n \n ListNode* mergeKLists(vector<ListNode*>& lists)\n {\n int n=lists.size();\n if(lists.size()==0) return NULL;\n while(n>1){\n \n for(int i=0;i<n/2;i++)\n lists[i] = mergeTwoSorted(lists[i], lists[n-i-1]);\n n = (n+1)/2;\n }\n return lists.front();\n }\n};\n```\n\n----\n**Approach - 5 : USING MAX HEAP**\n**Time :** **`35 ms`**\n\n```\nclass Solution {\npublic:\n\n ListNode* mergeKLists(vector<ListNode*>& lists) {\n \n if(lists.empty()) return NULL;\n \n // MAX heap\n priority_queue<pair<int, ListNode*>> pq; // (value, Node address)\n int n=lists.size();\n \n for(int i=0;i<n;i++)\n {\n ListNode *p = lists[i];\n while(p)\n {\n pq.push({-p->val, p}); // acts as min heap\n p = p->next;\n }\n }\n \n ListNode* head=NULL;\n ListNode* last=NULL;\n \n if(pq.empty()) return head;\n \n head=pq.top().second;\n last=pq.top().second;\n pq.pop();\n \n \n while(!pq.empty())\n {\n last->next = pq.top().second;\n last = pq.top().second;\n pq.pop();\n \n }\n last->next=NULL;\n \n return head;\n \n }\n};\n```\n*Thanks for Upvoting !*\n\uD83D\uDE42\n**It highly motivates me for writing a such clustered posts in which all approaches will be present in a single place.**
2,237
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
3,045
31
# Intuition:\nThe problem can be solved by merging two sorted linked lists at a time. If we have K linked lists, we can merge the first and second linked lists, then merge the result with the third linked list, and so on. This process will result in a single sorted linked list containing all elements.\n\n# Approach:\n\n1. Define a function mergeTwoLists that takes two sorted linked lists as input and merges them into a single sorted linked list using a recursive approach.\n2. In the mergeKLists function, initialize a pointer ans to NULL.\n3. Iterate over the input vector lists, and at each iteration, merge ans with the current linked list using the mergeTwoLists function.\n4. Return ans.\n# Complexity:\n\n- Time complexity: \nThe time complexity of this solution is O(N log k), where N is the total number of elements in all linked lists, and k is the number of linked lists. The reason for this complexity is that we are merging two lists at a time, and the number of merged lists is reduced by a factor of 2 at each iteration. Thus, the total number of iterations is log k. In each iteration, we perform N comparisons and updates, so the total time complexity is O(N log k).\n\n- Space Complexity:\nThe space complexity of this solution is O(1) since we are not using any additional data structures. The only extra space used is the recursion stack space, which is O(log k) for the recursive approach used in mergeTwoLists.\n\n---\n# C++\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {\n // Recursive Approach \n ListNode* ptr1 = list1;\n ListNode* ptr2 = list2;\n if(ptr1 == NULL){\n return list2;\n }\n if(ptr2 == NULL){\n return list1;\n }\n if(ptr1->val < ptr2->val){\n ptr1->next = mergeTwoLists(ptr1->next, ptr2);\n return ptr1;\n }\n else{\n ptr2->next = mergeTwoLists(ptr1, ptr2->next);\n return ptr2;\n }\n }\n ListNode* mergeKLists(vector<ListNode*>& lists) {\n ListNode* ans = NULL;\n int count=0;\n while(count<lists.size()){\n ans = mergeTwoLists(ans,lists[count]);\n count++;\n }\n return ans;\n }\n};\n```\n\n---\n# Java\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode mergeTwoLists(ListNode l1, ListNode l2) {\n if (l1 == null) {\n return l2;\n }\n if (l2 == null) {\n return l1;\n }\n if (l1.val < l2.val) {\n l1.next = mergeTwoLists(l1.next, l2);\n return l1;\n } else {\n l2.next = mergeTwoLists(l1, l2.next);\n return l2;\n }\n }\n\n public ListNode mergeKLists(ListNode[] lists) {\n ListNode ans = null;\n for (int i = 0; i < lists.length; i++) {\n ans = mergeTwoLists(ans, lists[i]);\n }\n return ans;\n }\n}\n\n```\n---\n# JavaScript\n```\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n */\n/**\n * @param {ListNode[]} lists\n * @return {ListNode}\n */\nvar mergeTwoLists = function(l1, l2) {\n if (!l1) {\n return l2;\n }\n if (!l2) {\n return l1;\n }\n if (l1.val < l2.val) {\n l1.next = mergeTwoLists(l1.next, l2);\n return l1;\n } else {\n l2.next = mergeTwoLists(l1, l2.next);\n return l2;\n }\n};\n\nvar mergeKLists = function(lists) {\n let ans = null;\n for (let i = 0; i < lists.length; i++) {\n ans = mergeTwoLists(ans, lists[i]);\n }\n return ans;\n};\n\n```\n---\n# Python\n### Different Approach\n- To avoid the "Time Limit Exceeded" error, we can use a more efficient approach using a min-heap or priority queue.\n```\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n\nclass Solution(object):\n def mergeKLists(self, lists):\n # Create a min-heap and initialize it with the first node of each list\n heap = []\n for i in range(len(lists)):\n if lists[i]:\n heapq.heappush(heap, (lists[i].val, i))\n\n # Create a dummy node to build the merged list\n dummy = ListNode(0)\n current = dummy\n\n # Merge the lists using the min-heap\n while heap:\n val, index = heapq.heappop(heap)\n current.next = lists[index]\n current = current.next\n lists[index] = lists[index].next\n if lists[index]:\n heapq.heappush(heap, (lists[index].val, index))\n\n return dummy.next\n\n```\n> # ***Thanks For Voting***
2,243
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
14,746
124
```\nclass Solution {\npublic:\n ListNode* merge2Lists(ListNode* l1, ListNode* l2) {\n if (!l1) return l2;\n if (!l2) return l1;\n ListNode* head = l1->val <= l2->val? l1 : l2;\n head->next = l1->val <= l2->val ? merge2Lists(l1->next, l2) : merge2Lists(l1, l2->next);\n return head;\n }\n \n ListNode* mergeKLists(vector<ListNode*>& lists) {\n if (lists.size() == 0) return NULL;\n \n ListNode* head = lists[0];\n \n for (int i = 1; i < lists.size(); i++)\n head = merge2Lists(head, lists[i]);\n \n return head;\n }\n};\n```\n**Like it? please upvote...**
2,244
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
596
6
# Intuition\nThe problem can be solved by merging two sorted linked lists at a time. If we have K linked lists, we can merge the first and second linked lists, then merge the result with the third linked list, and so on. This process will result in a single sorted linked list containing all elements.\n\n# Approach\nDefine a function mergeTwoLists that takes two sorted linked lists as input and merges them into a single sorted linked list using a recursive approach.\nIn the mergeKLists function, initialize a pointer ans to NULL.\nIterate over the input vector lists, and at each iteration, merge ans with the current linked list using the mergeTwoLists function.\nReturn ans.\n\n\n# Complexity\n- Time complexity:\nThe time complexity of this solution is O(N log k), where N is the total number of elements in all linked lists, and k is the number of linked lists. The reason for this complexity is that we are merging two lists at a time, and the number of merged lists is reduced by a factor of 2 at each iteration. Thus, the total number of iterations is log k. In each iteration, we perform N comparisons and updates, so the total time complexity is O(N log k).\n\n- Space complexity:\nThe space complexity of this solution is O(1) since we are not using any additional data structures. The only extra space used is the recursion stack space, which is O(log k) for the recursive approach used in mergeTwoLists.\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode mergeKLists(ListNode[] lists) {\n if (lists == null || lists.length == 0) {\n return null;\n }\n return mergeKListsHelper(lists, 0, lists.length - 1);\n }\n \n private ListNode mergeKListsHelper(ListNode[] lists, int start, int end) {\n if (start == end) {\n return lists[start];\n }\n if (start + 1 == end) {\n return merge(lists[start], lists[end]);\n }\n int mid = start + (end - start) / 2;\n ListNode left = mergeKListsHelper(lists, start, mid);\n ListNode right = mergeKListsHelper(lists, mid + 1, end);\n return merge(left, right);\n }\n \n private ListNode merge(ListNode l1, ListNode l2) {\n ListNode dummy = new ListNode(0);\n ListNode curr = dummy;\n \n while (l1 != null && l2 != null) {\n if (l1.val < l2.val) {\n curr.next = l1;\n l1 = l1.next;\n } else {\n curr.next = l2;\n l2 = l2.next;\n }\n curr = curr.next;\n }\n \n curr.next = (l1 != null) ? l1 : l2;\n \n return dummy.next;\n }\n}\n```
2,245
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
24,000
168
**Python 2 Solution:**\n```\ndef mergeKLists_Python2(self, lists):\n\th = []\n\thead = tail = ListNode(0)\n\tfor i in lists:\n\t\tif i:\n\t\t\theapq.heappush(h, (i.val, i))\n\n\twhile h:\n\t\tnode = heapq.heappop(h)[1]\n\t\ttail.next = node\n\t\ttail = tail.next\n\t\tif node.next:\n\t\t\theapq.heappush(h, (node.next.val, node.next))\n\n\treturn head.next\n```\n\n**Python 3:** \nThe above solution works fine with Python 2.However, with Python3 it gives Type Error:\nTypeError: \'<\' not supported between instances of \'ListNode\' and \'ListNode\'\n**This error occurs because the cmp() special method is no longer honored in Python 3**\n\nHere are the two ways we can solve this problem:\n**a) Implement eq, lt methods** \n\t\nOne of the solution would be to provide `__eq__ and __lt__` method implementation to `ListNode` class\n```\ndef mergeKLists_Python3(self, lists):\n\tListNode.__eq__ = lambda self, other: self.val == other.val\n\tListNode.__lt__ = lambda self, other: self.val < other.val\n\th = []\n\thead = tail = ListNode(0)\n\tfor i in lists:\n\t\tif i:\n\t\t\theapq.heappush(h, (i.val, i))\n\n\twhile h:\n\t\tnode = heapq.heappop(h)[1]\n\t\ttail.next = node\n\t\ttail = tail.next\n\t\tif node.next:\n\t\t\theapq.heappush(h, (node.next.val, node.next))\n\n\treturn head.next\n```\n\n**b) Fix heapq** \n\nThe problem while adding `ListNode` objects as tasks is that the Tuple comparison breaks for (priority, task) pairs if the priorities are equal and the tasks do not have a default comparison order. The solution is to store entries as 3-element list including the priority, an entry count, and the task.\nThe entry count serves as a tie-breaker so that two tasks with the same priority are returned in the order they were added.\nAnd since no two entry counts are the same, the tuple comparison will never attempt to directly compare two tasks.\n\n```\ndef mergeKLists_heapq(self, lists):\n\th = []\n\thead = tail = ListNode(0)\n\tfor i in range(len(lists)):\n\t\theapq.heappush(h, (lists[i].val, i, lists[i]))\n\n\twhile h:\n\t\tnode = heapq.heappop(h)\n\t\tnode = node[2]\n\t\ttail.next = node\n\t\ttail = tail.next\n\t\tif node.next:\n\t\t\ti+=1\n\t\t\theapq.heappush(h, (node.next.val, i, node.next))\n\n\treturn head.next\n```\n\t
2,250
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
2,574
25
```\nOkay, so for this problem we are given several linked list in our array. \nEach linked list is sorted in asscending order & we merge all the list together to be one sorted linked list. \nThere are many ways to solve this problem. \n```\nLet\'s take an example,\n\n**Input**: lists = [[1,3,4],[5,6,7],[3,4,5]]\n**Output**: [ 1, 3, 3, 4, 4, 5, 5, 6, 7 ]\n```\nThe brute force approach is,\n```\nWe can simply iterate over all the list node & add them into an array. Then we sort the array & loop through to make the connection b/w nodes. And this will take **Time complexity - BigO(NlogN)** & **Space complexity - BigO(N)**\n\n![image]()\n\n```\nclass Solution {\n public ListNode mergeKLists(ListNode[] lists) {\n if(lists == null || lists.length == 0) return null;\n \n ListNode head = new ListNode(0); // dummy node head\n ListNode temp = head; // taking into temporary variable\n List<Integer> l = new ArrayList<>();\n for(ListNode list : lists){ // adding all the values in the list\n while(list != null){\n l.add(list.val);\n list = list.next;\n }\n }\n Collections.sort(l); // sorting that list we get above\n for(int val : l){ // iterating over the list & creating new single linked list\n temp.next = new ListNode(val);\n temp = temp.next;\n }\n return head.next;\n }\n}\n```\n\n\n<hr>\n<hr>\n\n```\nLet\'s Optimize a more bit.\n```\n\n<hr>\n<hr>\n\nLet\'s take an example,\n\n**Input**: lists = [[1,2,3,4],[2,3,4,5],[1,1,2,3]]\n**Output**: [ 1, 3, 3, 4, 4, 5, 5, 6, 7 ]\n\n![image]()\n\nAs you see that each of these 3 lists are sorted in itself. \n* We compare the 1\'st three values of the list & pick which ever is the lowest.\n\n\n* We will have a dummy node to put that smallest value next to the dummy node. \n* Now from which ever list we have selected this node will move the pointer to it\'s next node\n* Similarly, we will compare the value again & over again and which ever is the smallest we put that in result list.\n\n![image]()\n\nWe continuously doing this, until we reach end of all the list.\n\n*I hope you got the idea,* **let\'s code it up:**\n```\nclass Solution {\n public ListNode mergeKLists(ListNode[] lists) {\n if(lists == null || lists.length == 0) return null; // base case\n \n ListNode head = new ListNode(0); // dummy node created & you can chose any value of your choice, I choose 0 "Because we indian invented that"\n ListNode temp = head;\n \n while(true){ // running infinite\n int p = 0; // point to list with minimum value\n for(int i = 0; i < lists.length; i++){\n if(lists[p] == null || (lists[i] != null && lists[p].val > lists[i].val)){\n p = i;\n }\n }\n if(lists[p] == null){ // it means no value present\n break;\n }\n temp.next = lists[p];\n temp = temp.next;\n lists[p] = lists[p].next;\n }\n return head.next;\n }\n}\n```\nANALYSIS :-\n* **Time Complexity :-** BigO(N * K) where N is no. of nodes & K is size of the lists\n\n* **Space Complexity :-** BigO(N) \n\n\n<hr>\n<hr>\n\n```\nLet\'s move to more Optimal Approach. \n```\n\n<hr>\n<hr>\n\n\n***So, the knowledge of Merge Sort Algorithm is very prevalent here. It will involved a divide n conquer approach.***\n\nSo, there are 2 step\'s that we need to perform.\n1. The 1st step is dividing the lists recursively until arriving at our base case.\n2. And our 2nd step is to merge the lists together to be in sorted order.\n\nThe intution behind this approach is we will be merging together sorted lists in multiple parts of the array recursively, **hence we using divide and conquer.**\n\nLet\'s take one more example:\n```\nInput: lists = [[1,4,5],[1,3,4],[2,6]]\nOutput: [1,1,2,3,4,4,5,6]\n```\n* So, what i say is, at each step we gonna have a start & end index. Start is going to be at 0 & end is going to be at 2.\n\n\n* As you can see start is left most side of our array i.e. `[1, 4, 5]`\n* And end is on our right most side of our array i.e. `[2, 6]`\n* So, with the start & end values, we are now going to compute our mid point. If we do our mid = start + end / 2 i.e. `mid = (0 + 2 ) / 2 = 1`\n* And what this is telling us, we gonna split our array base on this mid point. So, the left side will be `[Start, mid] i.e. [ [1, 4, 5], [1, 3, 4] ]`\n* And our right side will be `[mid + 1, end] i.e. [ [2, 6] ]`\n\n![image]()\n\nAnd we gonna continueosuly do this until we arrive at our base cases where our start index is equals to our end index\n\n* So, after splitting at index 1 we now have the following list **[ [1, 4, 5], [1, 3, 4] ]** & we do this same logic recursively over and over we arrive at the base cases. \n* So, now let\'s do the same thing with left side again. Now our **start = 0 & end = 1**. If we calculate mid again i.e. `mid = (0 + 1) / 2 = 0 `\n* We gonna have one list which is `[ [1, 4, 5] ]` & another list which is `[ [1, 3, 4] ]`\n* So, now as you can see after we did that, the division resulted it into 2 base cases, since each list is on it\'s own.\n\n![image]()\n\nWhat does this mean\'s that we just need to go back, up the chain and merge the list together.\n\n* So, `[1,4,5]` get return from our recursive call\n* And `[1,3,4]` get returns from a separate recursive call\n* ANd then, we going to merge them back together and that would result in array of `[[1,,1,3,4,45]]`\n* Now if we go back & look at our right subtree, in the previous division step we did. We were left with the base case of `[[2,6]]`, this will get return\n\n![image]()\n\nAnd finally we gonna merge `[[2,6]]` with previously merge array. And merging these together gives us `[ [ 1, 1, 2, 3, 4, 4, 5, 6 ] ]` which is our final answer.\n\n![image]()\n\n*Now, I hope approach is crystal clear,* **let\'s code it**\n\n```\nclass Solution {\n public ListNode mergeKLists(ListNode[] lists) {\n // Base Condition\n if(lists == null || lists.length == 0) return null;\n // Creating helper function helps in dividing and conquer approach\n return getMid(lists, 0, lists.length - 1); // created start & end index\n }\n private ListNode getMid(ListNode lists[], int start, int end){\n // Handle base case, when start & end index are same\n if(start == end) return lists[start];\n int mid = start + (end - start) / 2; // calculating mid & why we writing in this way to handle index overflow\n ListNode left = getMid(lists, start, mid); // in left mid become our new end\n ListNode right = getMid(lists, mid + 1, end); // in right this time start is mid + 1\n \n return merge(left, right);// merge the left & right together\n }\n private ListNode merge(ListNode l1, ListNode l2){\n ListNode result = new ListNode(0); // created dummy node with any value of your choice, i choose 0 "Because we indian invented that"\n ListNode curr = result; // use this pointer to move over\n \n while(l1 != null || l2 != null){\n if(l1 == null){\n curr.next = l2; // bcz if l1 is null we know l2 must have value\n l2 = l2.next;\n }\n else if(l2 == null){\n curr.next = l1; // bcz if l2 is null we know l1 must have value\n l1 = l1.next;\n }else if(l1.val < l2.val){ // if we made up till this point we know they both have value & let\'s compare them\n curr.next = l1;\n l1 = l1.next;\n }\n else{\n curr.next = l2;\n l2 = l2.next;\n }\n curr = curr.next;\n }\n return result.next; // why we not return only result bcz, result has dummy value of 0\n }\n}\n```\nANALYSIS :-\n* **Time Complexity :-** BigO(N * log(K)) where N is no of nodes we have when we are merging 2 lists together. ANd log of K portion comes from our recursive func. getMid. K is the no. of recursive call that we going to have to make.\n\n* **Space Complexity :-** BigO(K) where K is also no. of recursive call that we going to have to make, since every time we make a recursive call it add to ours stack space
2,251
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
44,211
334
```\nclass Solution(object):\n def mergeKLists(self, lists):\n if not lists:\n return None\n if len(lists) == 1:\n return lists[0]\n mid = len(lists) // 2\n l, r = self.mergeKLists(lists[:mid]), self.mergeKLists(lists[mid:])\n return self.merge(l, r)\n \n def merge(self, l, r):\n dummy = p = ListNode()\n while l and r:\n if l.val < r.val:\n p.next = l\n l = l.next\n else:\n p.next = r\n r = r.next\n p = p.next\n p.next = l or r\n return dummy.next\n \n def merge1(self, l, r):\n if not l or not r:\n return l or r\n if l.val< r.val:\n l.next = self.merge(l.next, r)\n return l\n r.next = self.merge(l, r.next)\n return r\n```
2,254
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
1,132
6
# Intuition\nJust insert all the elements in a vector and sort it. Then make a new LL using vector\'s elements.\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(n)\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * ListNode(int x) : val(x), next(nullptr) {}\n * ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\n\nclass Solution {\npublic:\n ListNode* mergeKLists(vector<ListNode*>& lists) {\n vector<int> v;\n \n for(auto i:lists){\n while(i != NULL){\n v.push_back(i->val);\n i=i->next;\n }\n }\n \n if(v.size() == 0) return NULL;\n sort(v.begin(), v.end());\n \n ListNode* head = new ListNode(v[0]);\n ListNode* temp = head;\n \n for(int i=1; i<v.size(); i++){\n ListNode* num = new ListNode(v[i]);\n temp->next = num;\n temp = temp->next;\n }\n \n return head;\n }\n};\n```
2,260
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
82,089
261
from Queue import PriorityQueue\n class Solution(object):\n def mergeKLists(self, lists):\n dummy = ListNode(None)\n curr = dummy\n q = PriorityQueue()\n for node in lists:\n if node: q.put((node.val,node))\n while q.qsize()>0:\n curr.next = q.get()[1]\n curr=curr.next\n if curr.next: q.put((curr.next.val, curr.next))\n return dummy.next
2,261
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
79,054
306
I have seen lots of solutions confuse `priority queue` with `heap`. I find a good [link][1] and list the talk below.\n\n**Concept:**\n\n1.`Heap` is a kind of `data structure`. It is a name for a particular way of storing data that makes certain operations very efficient. We can use a tree or array to describe it.\n\n 18\n /\t\\\n 10\t 16\n / \\ / \\\n 9 5 8 12\n \n 18, 10, 16, 9, 5, 8, 12\n\n2.`Priority queue` is an `abstract datatype`. It is a shorthand way of describing a particular interface and behavior, and says nothing about the underlying implementation.\n\nA heap is a very good data structure to implement a priority queue. The operations which are made efficient by the heap data structure are the operations that the priority queue interface needs.\n\n\n**Implementation: c++** \n\n1.`priority_queue`: we can only get the top element (from ChiangKaiShrek's [solution][2])\n\n struct compare {\n bool operator()(const ListNode* l, const ListNode* r) {\n return l->val > r->val;\n }\n };\n ListNode *mergeKLists(vector<ListNode *> &lists) { //priority_queue\n priority_queue<ListNode *, vector<ListNode *>, compare> q;\n for(auto l : lists) {\n if(l) q.push(l);\n }\n if(q.empty()) return NULL;\n\n ListNode* result = q.top();\n q.pop();\n if(result->next) q.push(result->next);\n ListNode* tail = result; \n while(!q.empty()) {\n tail->next = q.top();\n q.pop();\n tail = tail->next;\n if(tail->next) q.push(tail->next);\n }\n return result;\n }\n\n2.`make_heap`: we can access all the elements (from my answer for that solution)\n\n static bool heapComp(ListNode* a, ListNode* b) {\n return a->val > b->val;\n }\n ListNode* mergeKLists(vector<ListNode*>& lists) { //make_heap\n ListNode head(0);\n ListNode *curNode = &head;\n vector<ListNode*> v; \n for(int i =0; i<lists.size(); i++){\n if(lists[i]) v.push_back(lists[i]);\n }\n make_heap(v.begin(), v.end(), heapComp); //vector -> heap data strcture\n \n while(v.size()>0){\n curNode->next=v.front();\n pop_heap(v.begin(), v.end(), heapComp); \n v.pop_back(); \n curNode = curNode->next;\n if(curNode->next) {\n v.push_back(curNode->next); \n push_heap(v.begin(), v.end(), heapComp);\n }\n }\n return head.next;\n }\n\nIf there is something wrong, please figure it out. Hoping to learn more about them.\n\n\n [1]: \n [2]:
2,263
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
1,508
27
```C++ []\nofstream ans("user.out");\nint main() {\n vector<int> v;\n v.reserve(1e4);\n string s;\n while (getline(cin, s)) {\n s.erase(remove(begin(s), end(s), \'[\'), end(s));\n s.erase(remove(begin(s), end(s), \']\'), end(s));\n for (auto &i: s) if (i == \',\') i = \' \';\n istringstream iss(s);\n int temp;\n v.clear();\n while (iss >> temp) v.push_back(temp);\n sort(v.begin(), v.end());\n ans << \'[\';\n for (int i = 0; i < v.size(); ++i) {\n if (i) ans << \',\';\n ans << v[i];\n }\n ans << "]\\n";\n }\n}\nclass Solution {\npublic:\n ListNode* mergeKLists(vector<ListNode*>& lists) {\n return nullptr;\n }\n};\n```\n\n```Python3 []\nf = open("user.out", \'w\')\nfor s in sys.stdin:\n print(\'[\', \',\'.join(\n map(str, sorted(int(v) for v in s.rstrip().replace(\'[\', \',\').replace(\']\', \',\').split(\',\') if v))), \']\', sep=\'\',\n file=f)\nexit(0)\n```\n\n```Java []\nclass Solution {\n\n ListNode merge(ListNode list1, ListNode list2) {\n\n if (list1 == null) {\n return list2;\n } else if (list2 == null) {\n return list1;\n }\n\n ListNode head = null, curr = head;\n ListNode curr1 = list1, curr2 = list2;\n while (curr1 != null && curr2 != null) {\n\n ListNode minNode = null;\n if (curr1.val < curr2.val) {\n minNode = curr1;\n curr1 = curr1.next;\n } else {\n minNode = curr2;\n curr2 = curr2.next;\n }\n\n if (head == null) {\n curr = head = minNode;\n } else {\n curr.next = minNode;\n curr = curr.next;\n }\n }\n\n if (curr1 != null) {\n curr.next = curr1;\n } else if (curr2 != null) {\n curr.next = curr2;\n }\n\n return head;\n }\n\n ListNode mergeSort(ListNode[] lists, int beg, int end) {\n\n if (beg == end) {\n return lists[beg];\n }\n\n int mid = (beg + end) / 2;\n ListNode list1 = mergeSort(lists, beg, mid);\n ListNode list2 = mergeSort(lists, mid + 1, end);\n ListNode head = merge(list1, list2);\n return head;\n }\n\n public ListNode mergeKLists(ListNode[] lists) {\n\n if (lists.length == 0) {\n return null;\n }\n return mergeSort(lists, 0, lists.length - 1);\n }\n}\n```\n
2,269
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
5,808
125
```\nListNode* mergeKLists(vector<ListNode*>& lists) {\n \n if(lists.empty()) return nullptr;\n \n priority_queue<pair<int,ListNode*>> pq;\n int n=lists.size();\n \n for(int i=0;i<n;i++)\n {\n while(lists[i]!=nullptr)\n {\n pq.push({-lists[i]->val,lists[i]});\n lists[i]=lists[i]->next;\n }\n }\n \n \n ListNode* head=nullptr;\n ListNode* k=nullptr;\n \n if(pq.empty()) return head;\n \n head=pq.top().second;\n k=pq.top().second;\n pq.pop();\n \n \n while(!pq.empty())\n {\n k->next=pq.top().second;\n k=pq.top().second;\n pq.pop();\n \n }\n k->next=NULL;\n \n return head==NULL?nullptr:head;\n \n }\n```
2,272
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
1,496
12
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) { this.val = val; }\n * ListNode(int val, ListNode next) { this.val = val; this.next = next; }\n * }\n */\nclass Solution {\n public ListNode mergeKLists(ListNode[] lists) {\n if (lists == null || lists.length == 0) {\n return null;\n }\n return mergeKListsHelper(lists, 0, lists.length - 1);\n }\n \n private ListNode mergeKListsHelper(ListNode[] lists, int start, int end) {\n if (start == end) {\n return lists[start];\n }\n if (start + 1 == end) {\n return merge(lists[start], lists[end]);\n }\n int mid = start + (end - start) / 2;\n ListNode left = mergeKListsHelper(lists, start, mid);\n ListNode right = mergeKListsHelper(lists, mid + 1, end);\n return merge(left, right);\n }\n \n private ListNode merge(ListNode l1, ListNode l2) {\n ListNode dummy = new ListNode(0);\n ListNode curr = dummy;\n \n while (l1 != null && l2 != null) {\n if (l1.val < l2.val) {\n curr.next = l1;\n l1 = l1.next;\n } else {\n curr.next = l2;\n l2 = l2.next;\n }\n curr = curr.next;\n }\n \n curr.next = (l1 != null) ? l1 : l2;\n \n return dummy.next;\n }\n}\n\n```
2,273
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
269
6
```\nclass Solution {\npublic:\n ListNode* mergeKLists(vector<ListNode*>& lists) {\n map<int, int> mp;\n int k = lists.size();\n\n for (int i=0; i<k; i++) {\n ListNode *node = lists[i];\n while (node) {\n mp[node->val]++;\n node = node->next;\n }\n }\n\n ListNode* res = new ListNode();\n ListNode* head = res;\n\n for (auto [num, freq]: mp) {\n while (freq--) {\n res->next = new ListNode(num);\n res = res->next;\n }\n }\n\n return head->next;\n }\n};\n```
2,276
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
null
2,275
6
```\nclass Solution {\npublic:\n void it(ListNode* &t,int v){\n ListNode* s=new ListNode(v);\n t->next=s;\n t=t->next;\n }\n ListNode* mergeKLists(vector<ListNode*>& l) {\n vector<int>v;\n if(l.size()==0){//base case\n return NULL;\n }\n for(int p=0;p<l.size();p++){\n ListNode* a=l[p];\n while(a){\n v.push_back(a->val);\n a=a->next;\n }\n }\n if(v.size()==0){\n return NULL;\n }\n sort(v.begin(),v.end());\n\t\t//sorted vector\n ListNode* s=new ListNode(v[0]);\n ListNode* t=s;\n for(int p=1;p<v.size();p++){\n it(t,v[p]);//adding to tail\n }\n return s;\n }\n};\n```
2,291