question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
check-if-the-sentence-is-pangram | [ Go Solution ]Great explanation and Full Description | go-solution-great-explanation-and-full-d-iuhm | Intuition\nThe problem is asking us to determine if the input sentence is a pangram, i.e., it contains every letter of the alphabet at least once. To solve this | sansaian | NORMAL | 2023-07-27T06:37:02.462235+00:00 | 2023-07-27T06:37:02.462257+00:00 | 92 | false | # Intuition\nThe problem is asking us to determine if the input sentence is a pangram, i.e., it contains every letter of the alphabet at least once. To solve this problem, we can iterate through each character in the sentence and store each unique character in a data structure. If the total number of unique characters is 26 (the number of letters in the English alphabet), we know that the sentence is a pangram.\n\n# Approach\nThe approach in this implementation is to use a map data structure, where each character in the sentence is a key. We iterate over each character in the sentence, adding new characters to the map. This ensures each character only appears once in the map, since map keys are unique. Finally, we check if the size of the map is 26. If so, this means that the sentence is a pangram; otherwise, it\'s not.\n\n# Complexity\n- Time complexity: The time complexity is O(n), where n is the length of the sentence. This is because we\'re iterating through each character in the sentence once.\n- Space complexity: The space complexity is also O(n), where n is the length of the sentence. This is the space used by the map to store unique characters. In the worst case, if each character in the sentence is unique, we\'d have to store every character in the map. Note that since the map\'s size won\'t exceed 26 (the number of letters in the alphabet), we could also argue that the space complexity is O(1), or constant.\n\n# Code\n```\nfunc checkIfPangram(sentence string) bool {\n store:=make(map[rune]struct{})\n for _,ch:=range sentence{\n if _,ok:=store[ch];!ok{\n store[ch]=struct{}{}\n }\n }\n return len(store)==26\n}\n``` | 3 | 0 | ['Hash Table', 'String', 'Go'] | 0 |
check-if-the-sentence-is-pangram | Easy Python solution | easy-python-solution-by-pavellver-bbig | 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 | Pavellver | NORMAL | 2023-03-31T09:03:14.199416+00:00 | 2023-03-31T09:03:14.199454+00:00 | 220 | false | # 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 def checkIfPangram(self, sentence: str) -> bool:\n return len(set(sentence)) == 26\n``` | 3 | 0 | ['Python3'] | 0 |
check-if-the-sentence-is-pangram | easy | easy-by-bhavya32code-oef6 | 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 | Bhavya32code | NORMAL | 2023-01-09T01:09:52.008340+00:00 | 2023-01-09T01:09:52.008381+00:00 | 119 | false | # 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 bool checkIfPangram(string s) {\n vector<int>v(26);\n for(int p=0;p<s.length();p++){\n v[s[p]-97]++;\n }\n for(int p=0;p<26;p++){\n if(v[p]==0){\n return false;\n }\n }\n return true;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
check-if-the-sentence-is-pangram | Java Easy Solution | java-easy-solution-by-janhvi__28-vcj5 | \nclass Solution {\n public boolean checkIfPangram(String sentence) {\n Set<Character> set = new HashSet<Character>();\n int length = sentence. | Janhvi__28 | NORMAL | 2022-11-07T15:14:04.199315+00:00 | 2022-11-07T15:14:04.199361+00:00 | 469 | false | ```\nclass Solution {\n public boolean checkIfPangram(String sentence) {\n Set<Character> set = new HashSet<Character>();\n int length = sentence.length();\n for (int i = 0; i < length; i++) {\n char c = sentence.charAt(i);\n if (c >= \'a\' && c <= \'z\')\n set.add(c);\n }\n return set.size() == 26;\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
check-if-the-sentence-is-pangram | 0ms solution | 0ms-solution-by-coding_menance-djoo | C++ code\n\nclass Solution {\npublic:\n bool checkIfPangram(string sentence) {\n vector<short int> s(26);\n\n // add 1 to corresponding ascii i | coding_menance | NORMAL | 2022-10-27T06:00:23.176129+00:00 | 2022-10-27T06:00:23.176180+00:00 | 49 | false | # C++ code\n```\nclass Solution {\npublic:\n bool checkIfPangram(string sentence) {\n vector<short int> s(26);\n\n // add 1 to corresponding ascii indexes in vector\n for(char x:sentence) s[x-\'a\']++;\n\n // if any of the positions have 0, then that corresponding ascii character is missing\n // Eg, if sentence[3] is 0, then \'d\' is absent (since \'d\'-\'a\'=3)\n for (short int x:s) if (x==0) return false;\n \n // return true if all characters is present\n return true;\n }\n};\n```\n\nFeel free to ask away any doubts you have | 3 | 0 | ['C++'] | 0 |
check-if-the-sentence-is-pangram | 📌 Python solution using list | python-solution-using-list-by-vanderbilt-meae | \nclass Solution:\n def checkIfPangram(self, sentence: str) -> bool:\n counter = [0 for _ in range(97, 123)]\n \n for i in sentence:\n | vanderbilt | NORMAL | 2022-10-17T19:06:07.472215+00:00 | 2022-10-17T19:06:07.472262+00:00 | 1,086 | false | ```\nclass Solution:\n def checkIfPangram(self, sentence: str) -> bool:\n counter = [0 for _ in range(97, 123)]\n \n for i in sentence:\n counter[ord(i)-97] += 1\n \n for i in counter:\n if i == 0:\n return False\n return True\n``` | 3 | 0 | ['Array', 'Python', 'Python3'] | 0 |
check-if-the-sentence-is-pangram | Python solution using ASCII values | python-solution-using-ascii-values-by-am-6yjm | Here we are going to check the sentence with all 26 lower case english alphabets \n* chr(97) will be lowercase a so starting from there we will check whether ev | ambeersaipramod | NORMAL | 2022-10-17T19:02:14.249600+00:00 | 2022-10-17T19:02:14.249639+00:00 | 82 | false | * Here we are going to check the sentence with all 26 lower case english alphabets \n* `chr(97)` will be lowercase a so starting from there we will check whether every alphabet is there in the given sentence or not \n```\nclass Solution:\n def checkIfPangram(self, sentence: str) -> bool:\n for i in range(26):\n if chr(97+i) not in sentence:\n return False\n return True\n```\nA single liner code would be \n```\nreturn len(set(sentence))==26\n```\nHere we are converting the given sentence into set which wouldn\'t allow duplicate values and checking whether the length is 26 or not \n | 3 | 0 | ['Python', 'Python3'] | 0 |
check-if-the-sentence-is-pangram | ✅Easy Java solution||HashSet||Beginner Friendly🔥 | easy-java-solutionhashsetbeginner-friend-7mjh | If you really found my solution helpful please upvote it, as it motivates me to post such kind of codes and help the coding community, if you have some queries | deepVashisth | NORMAL | 2022-10-17T18:57:57.022247+00:00 | 2022-10-17T18:57:57.022288+00:00 | 103 | false | **If you really found my solution helpful please upvote it, as it motivates me to post such kind of codes and help the coding community, if you have some queries or some improvements please feel free to comment and share your views.**\n```\nclass Solution {\n public boolean checkIfPangram(String sentence) {\n HashSet<Character> hs = new HashSet<>();\n for(int i = 0 ; i < sentence.length() ; i ++){\n hs.add(sentence.charAt(i));\n if(hs.size() == 26){\n return true;\n }\n }\n return false;\n }\n}\n```\n**Happy Coding** | 3 | 0 | ['Java'] | 0 |
check-if-the-sentence-is-pangram | C++ | Easy O(1) space complexity. | c-easy-o1-space-complexity-by-meteoroid-hfuy | Approach \nUsed int(32 bits) to update the occurence of characters. Since we know that total count will not be greater than 26. \n Describe your approach to sol | meteoroid | NORMAL | 2022-10-17T17:29:23.110398+00:00 | 2022-10-18T11:17:00.178954+00:00 | 782 | false | # Approach \nUsed int(32 bits) to update the occurence of characters. Since we know that total count will not be greater than 26. \n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(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 bool checkIfPangram(string s) {\n int x=0;\n for(int i=0;i<s.size();i++){\n x = x | (1<<(s[i]-\'a\'));\n }\n return (x == (1<<26) -1);\n }\n};\n``` | 3 | 0 | ['C++'] | 2 |
check-if-the-sentence-is-pangram | Golang short solution | golang-short-solution-by-sansaian-txid | O(n) store O(n)\n\nfunc checkIfPangram(sentence string) bool {\n store:=make(map[rune]struct{})\n for _,ch:=range sentence{\n if _,ok:=store[ch];!o | sansaian | NORMAL | 2022-10-17T16:48:29.051338+00:00 | 2022-10-17T16:48:29.051376+00:00 | 419 | false | O(n) store O(n)\n```\nfunc checkIfPangram(sentence string) bool {\n store:=make(map[rune]struct{})\n for _,ch:=range sentence{\n if _,ok:=store[ch];!ok{\n store[ch]=struct{}{}\n }\n }\n return len(store)==26\n}\n``` | 3 | 0 | ['Go'] | 0 |
check-if-the-sentence-is-pangram | Easy java solution | easy-java-solution-by-siddhant_1602-69k1 | Intuition\nCalculating the frequency of each alphabet \n Describe your first thoughts on how to solve this problem. \n\n# Approach\nStoring the frequency of eac | Siddhant_1602 | NORMAL | 2022-10-17T14:44:04.444035+00:00 | 2022-10-17T14:44:04.444285+00:00 | 83 | false | # Intuition\nCalculating the frequency of each alphabet \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nStoring the frequency of each character and running a for loop to check whether if any character is missing or not\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(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 {\n public boolean checkIfPangram(String s) {\n int a[]=new int[26];\n for(char c:s.toCharArray())\n {\n a[c-\'a\']++;\n }\n for(int i=0;i<26;i++)\n {\n if(a[i]==0)\n {\n return false;\n }\n }\n return true;\n }\n}\n``` | 3 | 0 | ['Hash Table', 'String', 'Java'] | 0 |
check-if-the-sentence-is-pangram | Character Traversal Simple solution | character-traversal-simple-solution-by-d-peog | Traverse from a to z, if any character not found in the String return false.\n\nAt the end return true.\n\n\npublic boolean checkIfPangram(String s) {\n | dsharma007 | NORMAL | 2022-10-17T12:22:20.062176+00:00 | 2022-10-17T12:22:20.062237+00:00 | 64 | false | Traverse from `a to z`, if any character not found in the String return false.\n\nAt the end return true.\n\n```\npublic boolean checkIfPangram(String s) {\n \n for(char ch = \'a\'; ch <= \'z\'; ch++){\n if(s.indexOf(ch) == -1){\n return false;\n }\n }\n \n return true;\n }\n```\n\nPlease UpVote !!! | 3 | 0 | ['Java'] | 2 |
check-if-the-sentence-is-pangram | Easy Python | One-liner | easy-python-one-liner-by-tusharkhanna575-psqf | \nclass Solution:\n def checkIfPangram(self, sentence: str) -> bool:\n return(len(set(sentence))==26)\n | tusharkhanna575 | NORMAL | 2022-10-17T12:01:39.338844+00:00 | 2022-10-17T12:01:39.338877+00:00 | 302 | false | ```\nclass Solution:\n def checkIfPangram(self, sentence: str) -> bool:\n return(len(set(sentence))==26)\n``` | 3 | 0 | ['Python', 'Python3'] | 0 |
check-if-the-sentence-is-pangram | 📌C++ || 100% Runtime || Explained || ✅⭐⭐⭐ | c-100-runtime-explained-by-luvchaudhary-60kb | \n# My simple and fast solution (beats 100% Runtime\uD83D\uDD25and 82.91% in memory)\n\n\nclass Solution {\npublic:\n bool checkIfPangram(string sentence) {\ | Luvchaudhary | NORMAL | 2022-10-17T10:00:53.647237+00:00 | 2022-11-15T07:14:59.347487+00:00 | 1,295 | false | \n# **My simple and fast solution (beats 100% Runtime\uD83D\uDD25and 82.91% in memory)**\n\n```\nclass Solution {\npublic:\n bool checkIfPangram(string sentence) {\n int arr[26] = {0};\n\t\t//First traverse every letter of sentence in arr and increase its count if found\n for(int i=0; i<sentence.length(); i++){\n arr[sentence[i] - \'a\']++;\n }\n\t\t\n\t\t//Then traverse through the arr and see if any element has 0 count\n for(int i=0; i<26; i++){\n\t\t\t//if count = 0, then return False\n if(arr[i] == 0){\n return false;\n }\n }\n\t\t\n\t\t//if you have reached here then every letter is there so return True\n return true;\n }\n};\n\n```\n ** If you like the solution and understand it then Please Upvote.\uD83D\uDC4D**\n\t\t\t\t* PEACE OUT LUV\u270C\uFE0F*\n\n | 3 | 0 | ['Array', 'C', 'C++'] | 3 |
check-if-the-sentence-is-pangram | 3 line solution easy understanding c++ and unordered_map | 3-line-solution-easy-understanding-c-and-4b7l | 1 we declayer an unordered map of type \n2 loop through each letter in string and place it in unordered map\n3 if size of map is equal to 26 then all the letter | shivanantbhagat7 | NORMAL | 2022-10-17T08:28:30.804504+00:00 | 2022-10-17T08:28:30.804543+00:00 | 775 | false | 1 we declayer an unordered map of type <char,int>\n2 loop through each letter in string and place it in unordered map\n3 if size of map is equal to 26 then all the letters are included\n```\nclass Solution {\npublic:\n bool checkIfPangram(string sentence) {\n unordered_map<char,int> mappa;\n for(int i=0;i<sentence.size();++i)mappa[sentence[i]]++;\n return 26 == mappa.size();\n }\n}; | 3 | 0 | ['C'] | 1 |
insertion-sort-list | An easy and clear way to sort ( O(1) space ) | an-easy-and-clear-way-to-sort-o1-space-b-pcru | public ListNode insertionSortList(ListNode head) {\n \t\tif( head == null ){\n \t\t\treturn head;\n \t\t}\n \t\t\n \t\tListNode helper = new List | mingzixiecuole | NORMAL | 2015-02-07T23:43:30+00:00 | 2018-10-23T22:39:00.622213+00:00 | 87,331 | false | public ListNode insertionSortList(ListNode head) {\n \t\tif( head == null ){\n \t\t\treturn head;\n \t\t}\n \t\t\n \t\tListNode helper = new ListNode(0); //new starter of the sorted list\n \t\tListNode cur = head; //the node will be inserted\n \t\tListNode pre = helper; //insert node between pre and pre.next\n \t\tListNode next = null; //the next node will be inserted\n \t\t//not the end of input list\n \t\twhile( cur != null ){\n \t\t\tnext = cur.next;\n \t\t\t//find the right place to insert\n \t\t\twhile( pre.next != null && pre.next.val < cur.val ){\n \t\t\t\tpre = pre.next;\n \t\t\t}\n \t\t\t//insert between pre and pre.next\n \t\t\tcur.next = pre.next;\n \t\t\tpre.next = cur;\n \t\t\tpre = helper;\n \t\t\tcur = next;\n \t\t}\n \t\t\n \t\treturn helper.next;\n \t} | 413 | 12 | ['Java'] | 61 |
insertion-sort-list | Java / Python with Explanations | java-python-with-explanations-by-graceme-01g6 | For example,\n\nGiven 1 -> 3 -> 2 -> 4 - > null\n\ndummy0 -> 1 -> 3 -> 2 -> 4 - > null\n | |\n ptr toInsert\n-- locate ptr = 3 by | gracemeng | NORMAL | 2018-11-08T05:34:20.050070+00:00 | 2018-11-08T05:34:20.050134+00:00 | 12,416 | false | For example,\n```\nGiven 1 -> 3 -> 2 -> 4 - > null\n\ndummy0 -> 1 -> 3 -> 2 -> 4 - > null\n | |\n ptr toInsert\n-- locate ptr = 3 by (ptr.val > ptr.next.val)\n-- locate toInsert = ptr.next\n\ndummy0 -> 1 -> 3 -> 2 -> 4 - > null\n | |\n toInsertPre toInsert\n-- locate preInsert = 1 by preInsert.next.val > toInsert.val\n-- insert toInsert between preInsert and preInsert.next\n```\n****\n**Java**\n```\n public ListNode insertionSortList(ListNode ptr) { \n if (ptr == null || ptr.next == null)\n return ptr;\n \n ListNode preInsert, toInsert, dummyHead = new ListNode(0);\n dummyHead.next = ptr;\n\n while (ptr != null && ptr.next != null) {\n if (ptr.val <= ptr.next.val) {\n ptr = ptr.next;\n } else { \n toInsert = ptr.next;\n // Locate preInsert.\n preInsert = dummyHead;\n while (preInsert.next.val < toInsert.val) {\n preInsert = preInsert.next;\n }\n ptr.next = toInsert.next;\n // Insert toInsert after preInsert.\n toInsert.next = preInsert.next;\n preInsert.next = toInsert;\n }\n }\n \n return dummyHead.next;\n }\n```\n**Python**\n```\n def insertionSortList(self, head):\n\n dummyHead = ListNode(0)\n dummyHead.next = nodeToInsert = head\n \n while head and head.next:\n if head.val > head.next.val:\n # Locate nodeToInsert.\n nodeToInsert = head.next\n # Locate nodeToInsertPre.\n nodeToInsertPre = dummyHead\n while nodeToInsertPre.next.val < nodeToInsert.val:\n nodeToInsertPre = nodeToInsertPre.next\n \n head.next = nodeToInsert.next\n # Insert nodeToInsert between nodeToInsertPre and nodeToInsertPre.next.\n nodeToInsert.next = nodeToInsertPre.next\n nodeToInsertPre.next = nodeToInsert\n else:\n head = head.next\n \n return dummyHead.next\n```\n**(\u4EBA \u2022\u0348\u1D17\u2022\u0348)** Thanks for voting! | 150 | 0 | [] | 19 |
insertion-sort-list | Explained C++ solution (24ms) | explained-c-solution-24ms-by-jianchao-li-w319 | Keep a sorted partial list (head) and start from the second node (head -> next), each time when we see a node with val smaller than its previous node, we scan f | jianchao-li | NORMAL | 2015-05-27T15:45:36+00:00 | 2018-10-13T14:22:46.759816+00:00 | 29,006 | false | Keep a sorted partial list (`head`) and start from the second node (`head -> next`), each time when we see a node with `val` smaller than its previous node, we scan from the `head` and find the position that the node should be inserted. Since a node may be inserted before `head`, we create a `dummy` head that points to `head`.\n\n```cpp\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n ListNode* insertionSortList(ListNode* head) {\n ListNode* dummy = new ListNode(0);\n dummy -> next = head;\n ListNode *pre = dummy, *cur = head;\n while (cur) {\n if ((cur -> next) && (cur -> next -> val < cur -> val)) {\n while ((pre -> next) && (pre -> next -> val < cur -> next -> val)) {\n pre = pre -> next;\n }\n ListNode* temp = pre -> next;\n pre -> next = cur -> next;\n cur -> next = cur -> next -> next;\n pre -> next -> next = temp;\n pre = dummy;\n }\n else {\n cur = cur -> next;\n }\n }\n return dummy -> next;\n }\n};\n``` | 146 | 2 | ['Linked List', 'C++'] | 27 |
insertion-sort-list | ✅ [C++/Python/Java] 2 Simple Solution w/ Explanation | Swap values + Pointer Manipulation Approaches | cpythonjava-2-simple-solution-w-explanat-wapa | We need to sort the given linked list using insertion sort\n\n---\n\n\u2714\uFE0F Solution - I (Sort by Swapping Values)\n\nA pseudocode for standard insertion | archit91 | NORMAL | 2021-12-15T08:59:25.293036+00:00 | 2021-12-15T11:38:40.624307+00:00 | 7,171 | false | We need to sort the given linked list using insertion sort\n\n---\n\n\u2714\uFE0F ***Solution - I (Sort by Swapping Values)***\n\nA **pseudocode for standard insertion sort** might look like this -\n\n```c\nfor i = 0 to n\n\tcur = A[i] and j = i - 1\n\twhile j >= 0 and arr[j] > cur:\n\t\tarr[j+1] = arr[j] // shift right till we find greater than cur\n\t\tj = j-1\n\tarr[j+1] = cur // insert cur at correct pos\n```\n\nThis works for array and can even work for doubly linked-list where we can traverse backwards as well. However, for a singly linked list, we cant traverse backward and thus we cant directly implement in the above approach. \n\nSo, instead of beginning to left of current element and right-shifting each element till we find correct position for `cur`, we can modify the approach and begin inner iteration from 0 till we reach `i` (current element position) and swap the values whenever `A[j] > A[i]`. At the end, this will effectively achieve the same result as standard insertion sort does after each step.\n\n**C++**\n```cpp\nclass Solution {\npublic:\n ListNode* insertionSortList(ListNode* head) {\n for(auto cur = head; cur; cur = cur -> next) \n for(auto j = head; j != cur; j = j -> next) \n if(j -> val > cur -> val) \n swap(j -> val, cur -> val);\n return head; \n }\n};\n```\n\n**Python**\n```python\nclass Solution:\n def insertionSortList(self, head):\n cur = head\n while cur:\n j = head\n while j != cur:\n if j.val > cur.val: \n j.val, cur.val = cur.val, j.val\n j = j.next\n cur = cur.next\n return head\n```\n\n**Java**\n```java\nclass Solution {\n public ListNode insertionSortList(ListNode head) {\n for(ListNode cur = head; cur != null; cur = cur.next) \n for(ListNode j = head; j != cur; j = j.next) \n if(j.val > cur.val)\n j.val = j.val ^ cur.val ^ (cur.val = j.val); // swap \n return head;\n }\n}\n```\n\n***Time Complexity :*** <code>O(N<sup>2</sup>)</code>\n***Space Complexity :*** `O(1)`, only constant space is being used\n\n---\n\n\u2714\uFE0F ***Solution - II (Sort by Swapping Nodes)***\n\nIn the above solution, we required to iterate all the way from `head` till `cur` node everytime. Moreover, although each step outputs same result as insertion sort, it doesnt exactly functions like standard insertion sort algorithm in the sense that we are supposed to find & insert each element at correct position\n\nBasically, Insertion sort works by finding the correct position of `cur` in the sorted portion of list and inserting it at that position. This is particularly beneficial in case of linked list since we can remove `cur` from its position and insert `cur` at its correct position of sorted list in `O(1)` by simply manipulating pointers/links and thus we dont even need right-shift assignments as in case of arrays.\n\nWe can find correct position of `cur` by iterating in sorted portion of list till we find a node which has value less than cur. Then we remove `cur` from its original position and insert it at its correct position. The steps can be stated as -\n1. Update next pointer of `cur` to `j` which is the position before which `cur` needs to be inserted. **`cur -> next = j`**\n2. Update next pointer of previous node of `j` (`jPrev`) to `cur`. This is because `cur` is now inserted before `j` and thus `jPrev`\'s next node should point at cur. **`jPrev -> next = cur`**\n3. Update next pointer of previous node of `cur` (`curPrev`) to next of `cur`. This is because `cur` was removed from its original position and thus `curPrev` should point to next of `cur`. **`curPrev -> next = curNext`**\n4. The current node is now placed at its proper position and all pointers have been updated. Now, move on to next node and continue this process till we reach the end of list.\n\nThe below illustration will help better understand the process -\n\n```python\nConsider that we are at cur=2 and we found its correct position is before the node j=3\n\n jPrev j curPrev cur\n 1 \u2192 \'3\' \u2192 4 \u2192 5 \u2192 \'2\' \u2192 6 => 1 \u2192 2 \u2192 3 \u2192 4 \u2192 5 \u2192 6\n\n\n 2\uFE0F\u20E3\n \u21B1 \u2192 \u2192 \u2192 \u2192 \u21B4 curPrev cur\n=> 1 \u2508 \'3\' \u2192 4 \u2192 5 \u2508 \'2\' \u2508 6 => 1 \u2192 2 \u2192 3 \u2192 4 \u2192 5 \u2192 6\n \u2B11 \u2190 \u2190 \u2193 \u21B2 \u2191\n\t 1\uFE0F\u20E3 \u21B3 \u2192 \u2192 \u2B0F \n\t \t \t \t 3\uFE0F\u20E3\n```\n\nAnother thing to note is that `curPrev` only gets updated when `cur` is already at its correct position. In all other cases, curPrev will remain same becase `cur` is removed from its original position and inserted somewhere back. So when we move to the next node, `curPrev` will remain its previous node.\n\n**C++**\n```cpp\nclass Solution {\npublic:\n ListNode* insertionSortList(ListNode* head) {\n auto dummy = new ListNode(INT_MIN, head);\n for(auto curPrev = head, cur = head -> next; cur;) {\n auto jPrev = dummy, j = jPrev -> next, curNext = cur -> next;\n if(cur -> val > curPrev -> val) // cur already at correct position...so no need to update cur\n curPrev = cur; // only case where curPrev will need to be updated\n else {\n while(j -> val < cur -> val)\n jPrev = j, j = j -> next;\n cur -> next = j; // 1\uFE0F\u20E3\n jPrev -> next = cur; // 2\uFE0F\u20E3\n curPrev -> next = curNext; // 3\uFE0F\u20E3 \n }\n cur = curNext; // move to next node now \n }\n return dummy -> next;\n }\n};\n```\n\n<blockquote>\n<details>\n<summary><b><i>Maintain Less Variables</i></b></summary>\n\nWe can do away with using lesser variable names. Since we have access to next nodes, we can only maintain `jPrev` and `curPrev` and still have access to `j` and `cur`. The below solution has updated `j` and `cur` to denote `jPrev` and `curPrev` but kept the same name for simplicity.\n\n```cpp\nclass Solution {\npublic:\n ListNode* insertionSortList(ListNode* head) {\n auto dummy = new ListNode(INT_MIN, head), cur = head;\n while(cur -> next) \n if(cur -> next -> val > cur -> val) \n cur = cur -> next;\n else {\n auto j = dummy, curNextNext = cur -> next -> next;\n while(j -> next -> val < cur -> next -> val)\n j = j -> next;\n cur -> next -> next = j -> next;\n j -> next = cur -> next;\n cur -> next = curNextNext;\n }\n \n return dummy -> next;\n }\n};\n```\n\n</details>\n</blockquote>\n\n**Python**\n```python\nclass Solution:\n def insertionSortList(self, head):\n dummy, cur_prev, cur = ListNode(-1, head), head, head.next\n while cur:\n j_prev, j, cur_next = dummy, dummy.next, cur.next\n if cur.val > cur_prev.val:\n cur_prev = cur\n else: \n while j.val < cur.val:\n j_prev, j = j, j.next\n cur.next = j\n j_prev.next = cur\n cur_prev.next = cur_next\n cur = cur_next\n return dummy.next\n```\n\n**Java**\n```java\nclass Solution {\n public ListNode insertionSortList(ListNode head) {\n ListNode dummy = new ListNode(-1, head), curPrev = head, cur = head.next;\n while(cur != null) {\n ListNode jPrev = dummy, j = jPrev.next, curNext = cur.next;\n if(cur.val > curPrev.val) curPrev = cur;\n else {\n while(j.val < cur.val) {\n jPrev = j; \n j = j.next;\n }\n cur.next = j;\n jPrev.next = cur;\n curPrev.next = curNext;\n }\n cur = curNext;\n }\n return dummy.next;\n }\n}\n```\n\n***Time Complexity :*** <code>O(N<sup>2</sup>)</code>\n***Space Complexity :*** `O(1)`, only constant space is being used\n\n---\n---\n\n\uD83D\uDCBBIf there are any suggestions / questions / mistakes in my post, comment below \uD83D\uDC47 \n\n---\n--- | 71 | 4 | [] | 6 |
insertion-sort-list | Clean Java solution using a fake head | clean-java-solution-using-a-fake-head-by-vv9x | public ListNode insertionSortList(ListNode head) {\n ListNode curr = head, next = null;\n // l is a fake head\n ListNode l = new ListNode(0);\n | jeantimex | NORMAL | 2015-07-08T00:57:34+00:00 | 2018-09-03T02:14:14.160729+00:00 | 10,929 | false | public ListNode insertionSortList(ListNode head) {\n ListNode curr = head, next = null;\n // l is a fake head\n ListNode l = new ListNode(0);\n \n while (curr != null) {\n next = curr.next;\n \n ListNode p = l;\n while (p.next != null && p.next.val < curr.val)\n p = p.next;\n \n // insert curr between p and p.next\n curr.next = p.next;\n p.next = curr;\n curr = next;\n }\n \n return l.next;\n } | 64 | 2 | ['Java'] | 9 |
insertion-sort-list | [Python3] 188ms Solution (explanation with visualization) | python3-188ms-solution-explanation-with-bo3az | Idea\n- Add dummy_head before head will help us to handle the insertion easily\n- Use two pointers\n\t- last_sorted: last node of the sorted part, whose value i | EckoTan0804 | NORMAL | 2021-04-25T21:01:14.655499+00:00 | 2021-04-25T21:06:18.334122+00:00 | 4,570 | false | **Idea**\n- Add `dummy_head` before `head` will help us to handle the insertion easily\n- Use two pointers\n\t- `last_sorted`: last node of the sorted part, whose value is the largest of the sorted part\n\t- `cur`: next node of `last_sorted`, which is the current node to be considered\n\n\tAt the beginning, `last_sorted` is `head` and `cur` is `head.next`\n- When consider the `cur` node, there\'re 2 different cases\n\t- `last_sorted.val <= cur.val`: `cur` is in the correct order and can be directly move into the sorted part. In this case, we just move `last_sorted` one step forward\n\t\n\n\t- `last_sorted.val > cur.val`: `cur` needs to be inserted somewhere in the sorted part. In this case, we let `prev` start from `dummy_head` and iteratively compare `prev.next.val` and `cur.val`. If `prev.next.val > cur.val`, we insert `cur` between `prev` and `prev.next`\n\t- \n\n\n**Implementation**\n```python\nclass Solution:\n def insertionSortList(self, head: ListNode) -> ListNode:\n \n # No need to sort for empty list or list of size 1\n if not head or not head.next:\n return head\n \n # Use dummy_head will help us to handle insertion before head easily\n dummy_head = ListNode(val=-5000, next=head)\n last_sorted = head # last node of the sorted part\n cur = head.next # cur is always the next node of last_sorted\n while cur:\n if cur.val >= last_sorted.val:\n last_sorted = last_sorted.next\n else:\n # Search for the position to insert\n prev = dummy_head\n while prev.next.val <= cur.val:\n prev = prev.next\n \n # Insert\n last_sorted.next = cur.next\n cur.next = prev.next\n prev.next = cur\n \n cur = last_sorted.next\n \n return dummy_head.next\n```\n\n**Complexity**\n- Time: O(n^2)\n- Space: O(1) | 56 | 0 | ['Iterator', 'Python', 'Python3'] | 4 |
insertion-sort-list | Accepted Solution using JAVA | accepted-solution-using-java-by-isly-9rox | public class Solution {\n public ListNode insertionSortList(ListNode head) {\n ListNode helper=new ListNode(0);\n ListNode pre=helper;\n | isly | NORMAL | 2014-06-06T11:40:35+00:00 | 2018-10-18T01:41:15.624340+00:00 | 13,940 | false | public class Solution {\n public ListNode insertionSortList(ListNode head) {\n ListNode helper=new ListNode(0);\n ListNode pre=helper;\n ListNode current=head;\n while(current!=null) {\n pre=helper;\n while(pre.next!=null&&pre.next.val<current.val) {\n pre=pre.next;\n }\n ListNode next=current.next;\n current.next=pre.next;\n pre.next=current;\n current=next;\n }\n return helper.next;\n }\n} | 43 | 2 | [] | 2 |
insertion-sort-list | C++ EASY TO SOLVE || Detailed Explanation with dry run | c-easy-to-solve-detailed-explanation-wit-jfiu | Intuition:-\nNothing for intuition this time. Since the question is loud and clear that we need to use insertion sort[Also explained in the description of the q | Cosmic_Phantom | NORMAL | 2021-12-15T02:45:28.830071+00:00 | 2024-08-23T02:42:06.607182+00:00 | 6,894 | false | **Intuition:-**\nNothing for intuition this time. Since the question is loud and clear that we need to use insertion sort[Also explained in the description of the question] for sorting the linked list .\n*A tip -Do not get intimidated by the length of code have faith in yourself that you can understand.*\n\n**Algorithm:-**\n1. Let\'s create a `newHead ` as the name suggests it will be representating our final linked list. Initialize it to NULL.\n2. Now we will traverse our original linkedlist and seperate our head nodes one at a time in each iteration to insert them in the `newHead` initiated linkedlist\n3. During insertion in `newHead` we need to take care of three conditions \n* Condition 1: If this is the first node that is being inserted in the `newHead` the node will get insertd at `newHead `\n* Condition 2: After the the first insertion we need to check whether the next insertion will be in between or in the end of` newHead linkedlist`\n* Condition 3: To check the condition 2 we need this condition i.e we will traverse the newHead linkedlist using a temporary pointer "`root`" and find the appropriate position of the `temp` node\n4. Repeat process 2 and 3 until all the nodes are inserted to newHead\n\n[The three conditon we talked are in the form of **if** ,**elseif**, and **else** in the code given]\n\n\n**Before getting inside the code let\'s have a dry run :**\n\n\n\n**Code:-**\n```\nclass Solution {\npublic:\n ListNode* insertionSortList(ListNode* head) {\n ListNode* newHead = NULL;//initializing the newHead for our sorted linkedlist\n while(head){\n // Exluding node from the original linked list we will do this one at a time\n ListNode* temp = head;\n head = head->next;\n temp->next=NULL;\n \n //setting the first node of our final linked list \n if(newHead == NULL) newHead = temp;\n // if the position of element is at index 0 i.e. at the start (the temp node is the smallest of all the nodes that are currently present in the sorted linked list)\n else if(newHead->val >= temp->val){\n temp->next = newHead;\n newHead = temp;\n }\n // inserting the node anywhere in the middle or in the end depending upon the value of the temp node;\n else{\n ListNode* root = newHead;\n {\n while(root->next){\n if(temp->val > root->val and temp->val <= root->next->val){\n temp->next = root->next;\n root->next = temp;\n break;\n }\n root = root->next;\n } \n //inserting the temp node at the end\n if(root->next==NULL) root->next = temp;\n \n }\n }\n }\n //Our sorted linkedlist\n return newHead;\n }\n};\n```\n | 41 | 6 | ['Linked List', 'C', 'C++'] | 1 |
insertion-sort-list | [Python] Insertion Sort, explained | python-insertion-sort-explained-by-dbabi-xtqp | In this problem we are asked to implement insertion sort on singly-linked list data structure. And we do not really have a choice how to do it: we just need to | dbabichev | NORMAL | 2020-11-02T08:49:30.255056+00:00 | 2020-11-02T08:49:30.255099+00:00 | 2,309 | false | In this problem we are asked to implement insertion sort on singly-linked list data structure. And we do not really have a choice how to do it: we just need to apply definition of Insertion Sort. Imagine, that we already sorted some part of data, and we have something like:\n`1 2 3 7` **4** `6`,\nwhere by bold **4** I denoted element we need to insert on current step. How we can do it? We need to iterate over our list and find the place, where it should be inserted. Classical way to do it is to use **two pointers**: `prv` and `nxt`, stands for previous and next and stop, when value of `nxt` is greater than value of node we want ot insert. Then we insert this element into correct place, doing `curr.next = next, prv.next = curr`. Also, now we need to update our `curr` element: for that reason in the beginning of the loop we defined `curr_next = curr.next`, so we can update it now.\n\n**Complexity**: time complexity is `O(n^2)`, as Insertion sort should be: we take `O(n)` loops with `O(n)` loop inside. Space complexity is `O(1)`, because what we do is only change connections between our nodes, and do not create new data.\n\n```\nclass Solution:\n def insertionSortList(self, head):\n dummy = ListNode(-1)\n curr = head\n while curr:\n curr_next = curr.next\n prv, nxt = dummy, dummy.next\n while nxt:\n if nxt.val > curr.val: break\n prv = nxt\n nxt = nxt.next\n \n curr.next = nxt\n prv.next = curr\n curr = curr_next\n \n return dummy.next\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!** | 40 | 1 | [] | 2 |
insertion-sort-list | AC Python 192ms solution | ac-python-192ms-solution-by-dietpepsi-0870 | def insertionSortList(self, head):\n p = dummy = ListNode(0)\n cur = dummy.next = head\n while cur and cur.next:\n val = cur.nex | dietpepsi | NORMAL | 2015-10-08T23:40:01+00:00 | 2018-08-14T05:23:27.851586+00:00 | 10,775 | false | def insertionSortList(self, head):\n p = dummy = ListNode(0)\n cur = dummy.next = head\n while cur and cur.next:\n val = cur.next.val\n if cur.val < val:\n cur = cur.next\n continue\n if p.next.val > val:\n p = dummy\n while p.next.val < val:\n p = p.next\n new = cur.next\n cur.next = new.next\n new.next = p.next\n p.next = new\n return dummy.next\n\n\n # 21 / 21 test cases passed.\n # Status: Accepted\n # Runtime: 192 ms\n # 97.05%\n\nOf course, the solution is still O(n^2) in the worst case, but it can be faster than most implements under given test cases.\n\nTwo key points are: (1) a quick check see if the new value is already the largest (2) only refresh the search pointer p when the target is before it, in other words smaller. | 39 | 1 | ['Python'] | 8 |
insertion-sort-list | My C++ solution | my-c-solution-by-lxl-00jw | ListNode *insertionSortList(ListNode *head)\n {\n \tif (head == NULL || head->next == NULL)\n \t\treturn head;\n \n \tListNode *p = head->next;\n | lxl | NORMAL | 2015-04-30T02:02:32+00:00 | 2018-08-21T19:41:24.545767+00:00 | 4,125 | false | ListNode *insertionSortList(ListNode *head)\n {\n \tif (head == NULL || head->next == NULL)\n \t\treturn head;\n \n \tListNode *p = head->next;\n \thead->next = NULL;\n \n \twhile (p != NULL)\n \t{\n \t\tListNode *pNext = p->next; /*store the next node to be insert*/\n \t\tListNode *q = head;\n \n \t\tif (p->val < q->val) /*node p should be the new head*/\n \t\t{\n \t\t\tp->next = q;\n \t\t\thead = p;\n \t\t}\n \t\telse \n \t\t{\n \t\t\twhile (q != NULL && q->next != NULL && q->next->val <= p->val)\n \t\t\t\tq = q->next;\n \t\t\tp->next = q->next;\n \t\t\tq->next = p;\n \t\t}\n \n \t\tp = pNext;\n \t}\n \treturn head;\n } | 31 | 0 | [] | 7 |
insertion-sort-list | Concise python solution with comments | concise-python-solution-with-comments-by-hafp | def insertionSortList(self, head):\n cur = dummy = ListNode(0)\n while head:\n if cur and cur.val > head.val: # reset pointer only when | zhuyinghua1203 | NORMAL | 2015-12-02T01:15:12+00:00 | 2015-12-02T01:15:12+00:00 | 4,822 | false | def insertionSortList(self, head):\n cur = dummy = ListNode(0)\n while head:\n if cur and cur.val > head.val: # reset pointer only when new number is smaller than pointer value\n cur = dummy\n while cur.next and cur.next.val < head.val: # classic insertion sort to find position\n cur = cur.next\n cur.next, cur.next.next, head = head, cur.next, head.next # insert\n return dummy.next | 27 | 1 | ['Python'] | 6 |
insertion-sort-list | 7ms Java solution with explanation | 7ms-java-solution-with-explanation-by-bd-ihim | The only real modification here is to take advantage of the ability to add to both the front and end of a linked list in constant time. A typical insertion sor | bdwalker | NORMAL | 2016-03-15T17:53:14+00:00 | 2016-03-15T17:53:14+00:00 | 4,666 | false | The only real modification here is to take advantage of the ability to add to both the front and end of a linked list in constant time. A typical insertion sort would have to go through the entire array to find the new location to insert the element. If the element should be placed first in the array then we have to shift everything over. Thankfully, with a linked list we don't need to do this. The slight modification of keeping a pointer to the last node as well as the first dramatically increased the runtime of the algorithm. That being said, the speedup still has a lot to do with the ordering if the items in the array. \n\n public ListNode insertionSortList(ListNode head) {\n if (head == null || head.next == null)\n {\n return head;\n }\n\n ListNode sortedHead = head, sortedTail = head;\n head = head.next;\n sortedHead.next = null;\n \n while (head != null)\n {\n ListNode temp = head;\n head = head.next;\n temp.next = null;\n \n // new val is less than the head, just insert in the front\n if (temp.val <= sortedHead.val)\n {\n temp.next = sortedHead;\n sortedTail = sortedHead.next == null ? sortedHead : sortedTail;\n sortedHead = temp;\n }\n // new val is greater than the tail, just insert at the back\n else if (temp.val >= sortedTail.val)\n {\n sortedTail.next = temp;\n sortedTail = sortedTail.next;\n }\n // new val is somewhere in the middle, we will have to find its proper\n // location.\n else\n {\n ListNode current = sortedHead;\n while (current.next != null && current.next.val < temp.val)\n {\n current = current.next;\n }\n \n temp.next = current.next;\n current.next = temp;\n }\n }\n \n return sortedHead;\n } | 23 | 0 | [] | 2 |
insertion-sort-list | Python time limit is too tight | python-time-limit-is-too-tight-by-yintao-6ec8 | I have basically the same code in python and java (see below). python got TLE, but java was accepted. I propose to relax the python time limit a little bit.\n\n | yintaosong | NORMAL | 2014-11-09T18:48:11+00:00 | 2018-08-22T17:54:01.803720+00:00 | 5,904 | false | I have basically the same code in python and java (see below). python got TLE, but java was accepted. I propose to relax the python time limit a little bit.\n\n**Python**\n\n class Solution:\n # @param head, a ListNode\n # @return a ListNode\n def insertionSortList(self, head):\n srt = None\n while head:\n node = head\n head = head.next\n node.next = None\n srt = self.insertTo(srt, node)\n return srt\n \n def insertTo(self, head, node):\n node.next = head\n head = node\n while node.next and node.val > node.next.val:\n node.val, node.next.val = node.next.val, node.val\n node = node.next\n return head\n\n**java**\n\n public class Solution {\n public ListNode insertionSortList(ListNode head) {\n ListNode srt = null;\n while (head != null) {\n ListNode node = head;\n head = head.next;\n node.next = null;\n srt = insertTo(srt, node);\n }\n return srt;\n }\n \n public ListNode insertTo(ListNode head, ListNode node) {\n node.next = head;\n head = node;\n while (node.next != null && node.val > node.next.val) {\n node.val = node.val ^ node.next.val;\n node.next.val = node.val ^ node.next.val;\n node.val = node.val ^ node.next.val;\n node = node.next;\n }\n return head;\n }\n } | 22 | 1 | [] | 7 |
insertion-sort-list | C++ recursive insertion sort. | c-recursive-insertion-sort-by-oldcodingf-uc5j | \n ListNode* insertionSortList(ListNode* head) {\n if (head == nullptr || head->next == NULL)\n return head;\n ListNode *h = ins | oldcodingfarmer | NORMAL | 2015-12-06T19:05:30+00:00 | 2015-12-06T19:05:30+00:00 | 2,123 | false | \n ListNode* insertionSortList(ListNode* head) {\n if (head == nullptr || head->next == NULL)\n return head;\n ListNode *h = insertionSortList(head->next);\n if (head->val <= h->val) { // first case\n head->next = h;\n return head;\n }\n ListNode *node = h; // second case\n while (node->next && head->val > node->next->val)\n node = node->next;\n head->next = node->next;\n node->next = head;\n return h;\n } | 16 | 0 | ['Recursion', 'C++'] | 0 |
insertion-sort-list | ✔️ 100% Fastest Swift Solution, time: O(n log n), space: O(n). | 100-fastest-swift-solution-time-on-log-n-ed48 | \n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * public var val: Int\n * public var next: ListNode?\n * public init() { | sergeyleschev | NORMAL | 2022-04-13T05:52:48.516100+00:00 | 2022-04-13T05:53:23.228567+00:00 | 855 | false | ```\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * public var val: Int\n * public var next: ListNode?\n * public init() { self.val = 0; self.next = nil; }\n * public init(_ val: Int) { self.val = val; self.next = nil; }\n * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }\n * }\n */\nclass Solution {\n // - Complexity:\n // - time: O(n log n), where n is the number of nodes in the linked list.\n // - space: O(n)\n \n func insertionSortList(_ head: ListNode?) -> ListNode? {\n var nodes: [ListNode] = []\n var curr = head\n \n while curr != nil {\n nodes.append(curr!)\n curr = curr?.next\n }\n \n nodes.sort(by: { $0.val < $1.val })\n \n var newHead: ListNode?\n var prev: ListNode?\n \n for node in nodes {\n if newHead == nil {\n newHead = node\n }\n \n prev?.next = node\n prev = node\n }\n \n prev?.next = nil\n return newHead\n }\n\n}\n```\n\nLet me know in comments if you have any doubts. I will be happy to answer.\n\nPlease upvote if you found the solution useful. | 14 | 0 | ['Swift'] | 1 |
insertion-sort-list | C++ Simple and Short Explained Solution, No Extra Space | c-simple-and-short-explained-solution-no-rymg | Idea:\nWe start the new sorted list with a zero node, so that it will be easier to insert in every position.\nWe iterate through the list with the head pointer. | yehudisk | NORMAL | 2021-12-15T07:17:48.837292+00:00 | 2021-12-15T07:17:48.837328+00:00 | 1,182 | false | **Idea:**\nWe start the new sorted list with a zero node, so that it will be easier to insert in every position.\nWe iterate through the list with the `head` pointer.\nFor each node, we use the function `insert` to iterate through the new sorted list and find the right insertion position.\nWe return `new_head->next` because our zero node will always be first and we don\'t want it.\n\n**Time Complexity:** O(n^2)\n**Space Complexity:** O(1)\n```\nclass Solution {\npublic:\n void insert(ListNode* head, ListNode* node) {\n while (head->next && head->next->val < node->val) head = head->next;\n node->next = head->next;\n head->next = node;\n }\n \n ListNode* insertionSortList(ListNode* head) {\n ListNode* new_head = new ListNode(0);\n\n while (head) {\n ListNode* node = head;\n head = head->next;\n insert(new_head, node);\n }\n \n return new_head->next;\n }\n};\n```\n**Like it? please upvote!** | 13 | 2 | ['C'] | 1 |
insertion-sort-list | ✔️ [Python3] INSERTION SORT, Explained | python3-insertion-sort-explained-by-arto-al08 | The idea is to create a dummy node that would be the head of the sorted part of the list. Iterate over the given list and one by one add nodes to the sorted lis | artod | NORMAL | 2021-12-15T01:12:45.244091+00:00 | 2021-12-15T03:56:50.805258+00:00 | 2,782 | false | The idea is to create a dummy node that would be the head of the sorted part of the list. Iterate over the given list and one by one add nodes to the sorted list at the appropriate place following the insertion sort algorithm.\n\nTime: **O(n^2)**\nSpace: **O(1)**\n\nRuntime: 1677 ms, faster than **51.65%** of Python3 online submissions for Insertion Sort List.\nMemory Usage: 16.4 MB, less than **29.01%** of Python3 online submissions for Insertion Sort List.\n\n```\nclass Solution:\n def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n sort = ListNode() #dummy node\n\n cur = head\n while cur:\n sortCur = sort\n while sortCur.next and cur.val >= sortCur.next.val:\n sortCur = sortCur.next\n \n tmp, sortCur.next = sortCur.next, cur\n cur = cur.next\n sortCur.next.next = tmp\n \n return sort.next\n``` | 13 | 5 | ['Python3'] | 2 |
insertion-sort-list | [C++] Pointer-based Solution Explained, 100% Time, 90% Space | c-pointer-based-solution-explained-100-t-u241 | Ah, gotta love starting the day with classic algorithms you otherwise would just see again on textbooks and manuals :)\n\nIn order to proceed with this one, we | ajna | NORMAL | 2020-11-02T10:19:28.641842+00:00 | 2020-11-02T10:19:28.641873+00:00 | 1,761 | false | Ah, gotta love starting the day with classic algorithms you otherwise would just see again on textbooks and manuals :)\n\nIn order to proceed with this one, we need to first of all check if we are dealing with an empty list: if so, we just return `NULL`.\n\nOtherwise, we create 3 support variables, all `ListNode` pointers:\n* `tail`, initialised to be `head` will delimit up to where our sorted domain extends;\n* `curr` is the node we are currently considering and putting in sorted order;\n* `iter`, finally, it is a support variable for when we need to go and splice `curr` if it is not the newest minimum or the newest maximum; I know I might have not used it, just splicing `curr` so that it would bubble up to his position, but that seemed needlessly expensive and not worth saving the tiny amount of memory an extra pointer would cost us - so, unless your interviewer really wants you to consider other approaches (like dealing with devices of very little memory, but then not sure how they would handle linked lists), just discuss it quickly and make your own call of what is best.\n\nThen we have our main loop and we will proceed until we have something else to parse, that is to say as long as `tail->next`. Notice we do not need to check if `tail` exist, since we initialised it to `head` and we checked before that `head` has to be non `NULL`.\n\nInside our loops we will:\n* check if `curr` is the newest maximum and thus replace `tail` with it;\n* get the next value after `tail` out and assign it to `curr`;\n* check if `curr` is the newest minimum and thus replace `head` with it;\n* check for all the other cases, assigning `head` to `iter` initially and gradually increasing it, checking if `curr` fits between `iter` and `iter->next`.\n\nOnce we are done parsing the whole list, we return `head` :)\n\nThe code:\n\n```cpp\nclass Solution {\npublic:\n ListNode* insertionSortList(ListNode* head) {\n if (!head) return NULL;\n ListNode *tail = head, *curr, *iter;\n while (tail->next) {\n // checking if the next one is already the next bigger\n if (tail->val <= tail->next->val) {\n tail = tail->next;\n continue;\n }\n // taking a new node to parse, curr, out of the list\n curr = tail->next;\n tail->next = curr->next;\n // checking if curr will become the new head\n if (curr->val < head->val) {\n curr->next = head;\n head = curr;\n continue;\n }\n // all the other cases\n iter = head;\n while (iter != tail) {\n // checking when we can splice curr between iter and the following value\n if (curr->val < iter->next->val) {\n curr->next = iter->next;\n iter->next = curr;\n break;\n }\n // moving to the next!\n iter = iter->next;\n }\n }\n return head;\n }\n};\n``` | 12 | 2 | ['Graph', 'C', 'C++'] | 0 |
insertion-sort-list | Concise JavaScript solution | concise-javascript-solution-by-linfongi-rzgh | function insertionSortList(head) {\n var before = { val: -Number.MAX_VALUE, next: null };\n \n while (head) {\n var prev = befor | linfongi | NORMAL | 2016-06-04T03:47:12+00:00 | 2016-06-04T03:47:12+00:00 | 1,039 | false | function insertionSortList(head) {\n var before = { val: -Number.MAX_VALUE, next: null };\n \n while (head) {\n var prev = before;\n \n // find prev\n while (prev.next && prev.next.val < head.val) {\n prev = prev.next;\n }\n \n var next = head.next;\n head.next = prev.next;\n prev.next = head;\n head = next;\n }\n \n return before.next;\n } | 12 | 0 | [] | 2 |
insertion-sort-list | 147: Solution with step by step explanation | 147-solution-with-step-by-step-explanati-pyo3 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nThe solution involves iterating through the linked list, removing each no | Marlen09 | NORMAL | 2023-02-19T16:56:32.519211+00:00 | 2023-02-19T16:56:32.519257+00:00 | 2,817 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe solution involves iterating through the linked list, removing each node from the list, and then inserting it into the sorted portion of the list. The sorted portion of the list is initially just the first node, and grows with each iteration.\n\nThis solution has a time complexity of O(n^2) since in the worst case, we may need to iterate through the entire sorted portion of the list for each node in the unsorted portion of the list. The space complexity is O(1) since we are only manipulating the existing linked list and not creating any new data structures.\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 def insertionSortList(self, head: ListNode) -> ListNode:\n # Initialize the sorted portion of the list to be the first node\n sorted_head = ListNode(0)\n sorted_head.next = head\n sorted_tail = head\n \n # Start with the second node in the list, since the first node is already sorted\n curr = head.next\n \n while curr:\n # If the current node is greater than the tail of the sorted list, \n # it is already in the correct place, so just move on to the next node\n if curr.val >= sorted_tail.val:\n sorted_tail = curr\n curr = curr.next\n else:\n # Remove the current node from the list\n sorted_tail.next = curr.next\n \n # Find the correct position to insert the current node in the sorted list\n insert_pos = sorted_head\n while insert_pos.next.val < curr.val:\n insert_pos = insert_pos.next\n \n # Insert the current node into the sorted list\n curr.next = insert_pos.next\n insert_pos.next = curr\n \n # Move on to the next node in the unsorted portion of the list\n curr = sorted_tail.next\n \n return sorted_head.next\n\n``` | 11 | 0 | ['Linked List', 'Sorting', 'Python', 'Python3'] | 0 |
insertion-sort-list | ✅ [Python] Dummy Head || Clean and Easy to Understand with Detailed Explanation | python-dummy-head-clean-and-easy-to-unde-9pgv | Time Complexity : O(N2) \nSpace Complexity : O(1)\nDummy head can make the code more concise\n\nclass Solution(object):\n def insertionSortList(self, head):\ | linfq | NORMAL | 2021-12-15T03:34:05.073794+00:00 | 2021-12-15T03:46:00.283987+00:00 | 756 | false | **Time Complexity : O(N<sup>2</sup>) \nSpace Complexity : O(1)**\n**Dummy head can make the code more concise**\n```\nclass Solution(object):\n def insertionSortList(self, head):\n p, sl = head, ListNode() # sl is the sortedList with dummy head node.\n while p: # traverse the input linked list until None\n q = sl # q is the pre of current node of sortedList\n while q.next and q.next.val < p.val: # find the insertion position sequentially\n q = q.next\n p.next, q.next, p, q = q.next, p, p.next, q.next # insert p to q.next\n return sl.next # Note sl is the dummy head node\n```\n**If you have any question, feel free to ask. If you like the solution or the explaination, Please UPVOTE!** | 11 | 3 | ['Python'] | 1 |
insertion-sort-list | [Python] Actual Insertion Sort (solution article has inaccurate implementation) | python-actual-insertion-sort-solution-ar-x3el | Strictly speaking, in insertion sort, the intermeidate sorted list is iterated backwards (we first compare the new item with the last item and swap if they are | dadagda | NORMAL | 2021-12-15T01:23:07.398475+00:00 | 2021-12-15T01:23:07.398513+00:00 | 650 | false | Strictly speaking, in insertion sort, the intermeidate sorted list is iterated backwards (we first compare the new item with the last item and swap if they are out of order: this is repeated until new item is in order with previous item)\nHowever, in the solution article and some other posts, the intermediate sorted list is iterated forwards. This still produces correct output and the time complexity either way is still O(n^2). However, I believe we should implement the strict form for two reasons:\n* Insertion sort is particularly efficient for partially sorted array, and the benefit only exists if intermediate array is iterated backwards\n* Iterating singly linked list forwards is straightforward, but it\'s challenging to iterate it backwards. I figured this is what makes this problem challenging (and thus interesting)\n\nThe way I approach this is to keep intermediate sorted list in *descending* order to work around single linkage. After we have a descending array, we simply need to revert the linkage of the list by iterating the array one more time. For partially sorted array (list), this ensures a O(n) time complexity.\n\n```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 insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n # the intermidiate sorted list is in descending order so that strict insertion sort is possible\n # lastly, reverse the sorted list\n sentinel = ListNode(0, head)\n node = head.next\n head.next = None\n while node:\n next_node = node.next\n \n prior = sentinel\n while prior.next and prior.next.val > node.val:\n prior = prior.next\n node.next = prior.next\n prior.next = node\n \n node = next_node\n \n node = sentinel.next # node to be modified\n head = None # track the head of reversed list\n while node:\n next_node = node.next\n \n node.next = head\n head = node\n \n node = next_node\n \n return head\n``` | 11 | 0 | [] | 5 |
insertion-sort-list | Simple and clean java code | simple-and-clean-java-code-by-jinwu-8jyi | public ListNode insertionSortList(ListNode head) {\n\t\tListNode cur = head;\n\t\tListNode dummy = new ListNode(0), p;\n\t\twhile (cur != null) {\n\t\t\t//locat | jinwu | NORMAL | 2015-09-24T05:54:59+00:00 | 2015-09-24T05:54:59+00:00 | 2,934 | false | public ListNode insertionSortList(ListNode head) {\n\t\tListNode cur = head;\n\t\tListNode dummy = new ListNode(0), p;\n\t\twhile (cur != null) {\n\t\t\t//locate the insertion position.\n\t\t\tp = dummy;\n\t\t\twhile (p.next != null && cur.val > p.next.val) {\n\t\t\t\tp = p.next;\n\t\t\t}\n\t\t\t//insert between p and p.next.\n\t\t\tListNode pNext = p.next;\n\t\t\tp.next = cur;\n\t\t\tListNode next = cur.next;\n\t\t\tcur.next = pNext;\n\t\t\tcur = next;\n\t\t}\n\t\treturn dummy.next;\n\t} | 11 | 1 | ['Java'] | 4 |
insertion-sort-list | ✅💯🔥Simple Code🚀📌|| 🔥✔️Easy to understand🎯 || 🎓🧠Insertion Logical🔥|| Beginner friendly💀💯 | simple-code-easy-to-understand-insertion-69i2 | 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 | atishayj4in | NORMAL | 2024-07-27T20:51:05.028180+00:00 | 2024-08-01T19:51:48.573517+00:00 | 2,080 | false | # 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 */\n\n// //////////////////ATISHAY\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\\\\n// \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\JAIN////////////////// \\\\\n\nclass Solution {\n public ListNode insertionSortList(ListNode head) {\n ListNode dummy= new ListNode(0);\n ListNode current=head;\n while(current != null){\n ListNode prev=dummy;\n ListNode nextNode=current.next;\n while(prev.next!=null && prev.next.val < current.val){\n prev=prev.next;\n }\n current.next=prev.next;\n prev.next=current;\n current=nextNode;\n }\n return dummy.next;\n }\n}\n```\n\n | 10 | 0 | ['Linked List', 'C', 'Sorting', 'Python', 'C++', 'Java'] | 0 |
insertion-sort-list | For God's sake, don't try sorting a linked list during the interview | for-gods-sake-dont-try-sorting-a-linked-5bzi4 | \nclass Solution {\npublic:\n ListNode* insertionSortList(ListNode* head) {\n vector<int> nums;\n ListNode* temp = head;\n while(temp != | vaibhav4859 | NORMAL | 2021-12-15T11:59:16.695892+00:00 | 2021-12-15T11:59:16.695954+00:00 | 858 | false | ```\nclass Solution {\npublic:\n ListNode* insertionSortList(ListNode* head) {\n vector<int> nums;\n ListNode* temp = head;\n while(temp != NULL){\n nums.push_back(temp->val);\n temp = temp->next;\n }\n \n sort(nums.begin(), nums.end());\n temp = head;\n int i = 0;\n while(temp != NULL){\n temp->val = nums[i++];\n temp = temp->next;\n }\n return head;\n }\n};\n``` | 9 | 0 | ['Linked List', 'C', 'C++'] | 0 |
insertion-sort-list | easy to understand | easy-to-understand-by-shrivastava123-sua0 | \n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) | shrivastava123 | NORMAL | 2020-11-02T13:06:37.064526+00:00 | 2020-11-02T13:06:37.064565+00:00 | 848 | false | ```\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 insertionSortList(ListNode head) {\n if(head == null) return head;\n ListNode current = head.next;\n ListNode pre = head;\n while(current !=null){\n if(current.val>=pre.val){\n current = current.next;\n pre = pre.next;\n }\n else{\n pre.next = current.next;\n if(current.val<=head.val){ \n current.next = head;\n head = current;\n }\n else{\n ListNode search = head;\n while(search.next != null && search.next.val<current.val){\n search = search.next;\n }\n ListNode tmp = search.next;\n search.next = current;\n current.next = tmp;\n }\n current = pre.next;\n }\n }\n return head;\n }\n}\n``` | 9 | 0 | ['Java'] | 1 |
insertion-sort-list | Short, simple and fast c++ solution. No need for a dummy or similar to handle the new head creation. | short-simple-and-fast-c-solution-no-need-mrka | A lot of solutions allocate a dummy node with the intensions of using the dummy.next to point to the head of the new list. It\'s much simpler to instead use a p | christrompf | NORMAL | 2018-07-16T15:39:31.944729+00:00 | 2024-07-10T11:05:04.974539+00:00 | 638 | false | A lot of solutions allocate a dummy node with the intensions of using the dummy.next to point to the head of the new list. It\'s much simpler to instead use a pointer to a pointer that stores the address of either the pointer to the new head or the next pointer of the previous node. That way an update to whichever pointer is being pointed to (head or next), will either update the head directly or update the next of the previous node.\n\nIt\'s one of those things that\'s hard to explain with words. Saying a pointer pointing to a pointer, pointing to the head is just plain confusing. Walking through the code is the best way to understand.\n\n```\n ListNode* insertionSortList(ListNode* head) {\n ListNode* ret_head = nullptr;\n while (head) {\n ListNode* curr = head;\n head = head->next;\n \n // Use a pointer to pointer so that updating either ret_head or next of the previous node is\n // seemless and automatic.\n ListNode** prev_next = &ret_head;\n while (*prev_next && (*prev_next)->val < curr->val) {\n // Update prev_next to hold the address of the next pointer for the next node.\n prev_next = &(*prev_next)->next;\n }\n curr->next = *prev_next;\n *prev_next = curr;\n }\n return ret_head;\n }\n```\t\t | 9 | 1 | ['C', 'C++'] | 0 |
insertion-sort-list | My C++ solution by using pointer's pointer to do insertion. | my-c-solution-by-using-pointers-pointer-nk0c7 | Short and easy way to manipulate the list.\n \n\n class Solution {\n public:\n ListNode insertionSortList(ListNode head) {\n ListNode no | beeender | NORMAL | 2014-12-10T14:48:53+00:00 | 2014-12-10T14:48:53+00:00 | 2,178 | false | Short and easy way to manipulate the list.\n \n\n class Solution {\n public:\n ListNode *insertionSortList(ListNode *head) {\n ListNode **node = &head;\n while ((*node)) {\n bool flag = false;\n for (ListNode **cmp=&head; *cmp!=*node; cmp=&(*cmp)->next) {\n if ((*node)->val <= (*cmp)->val) {\n //Do insertion\n ListNode *tmp = *node;\n *node = (*node)->next;\n tmp->next = *cmp;\n *cmp = tmp;\n flag = true;\n break;\n }\n }\n //Node has been moved to the next already.\n if (flag) continue;\n node = &(*node)->next;\n }\n return head;\n }\n }; | 8 | 0 | [] | 3 |
insertion-sort-list | Easy To Understand code Of " insertion-sort-list" | easy-to-understand-code-of-insertion-sor-l820 | 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 | saurabh77008 | NORMAL | 2023-03-05T12:51:57.405739+00:00 | 2023-03-05T12:51:57.405766+00:00 | 1,231 | false | # 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 insertionSortList(ListNode head) {\n ListNode d = new ListNode(0, head);\n \n ListNode prev = head;\n ListNode curr = head.next;\n \n while (curr != null) {\n if (curr.val >= prev.val) {\n prev = curr;\n curr = curr.next;\n continue;\n }\n \n ListNode tmp = d;\n while (curr.val > tmp.next.val) {\n tmp = tmp.next;\n }\n \n prev.next = curr.next;\n curr.next = tmp.next;\n tmp.next = curr;\n curr = prev.next;\n }\n return d.next;\n }\n}\n``` | 7 | 0 | ['Linked List', 'Math', 'Sorting', 'Java'] | 1 |
insertion-sort-list | Simple Solution with step by step explaination | simple-solution-with-step-by-step-explai-aq61 | In this question, we have to perform insertion sorting on a linked list.\nTherefore, to first understand this, we first need to know about Insertion sort.\nIn I | paramsahai25 | NORMAL | 2023-01-18T07:22:27.319832+00:00 | 2023-01-18T07:22:27.319871+00:00 | 990 | false | In this question, we have to perform insertion sorting on a linked list.\nTherefore, to first understand this, we first need to know about Insertion sort.\nIn Insertion Sort, the array (linked list in this case) is divided into two parts, the unsorted and sorted parts.\n\nElements from unsorted part are picked and placed at their correct sorted position.\n\nIn this, we will be using three pointers *prev*, *curr* and *tmp* for storing previous values, current values and for storing head of the linked list.\n\nAt first, we have to check for edge cases, that is, whether the list is empty or has only one element. In both of these cases, we have to just simply return the head as no computation is required.\n\nAfter checking for the above mentioned cases, we have to perform sorting.\nFor every element, we have to check whether the element is at its correct position or not.\n\nIf the current value is less than the previous value, then we have to swap them, and furthermore, we have to now check the previously sorted part of the list as well including the currently sorted element.\n\nFor example consider the list:\n**[1,2,4,5,3]**\nIn this, [1,2,4,5] is sorted part but [3] is not.\nhere, **prev points to 5 and curr points to 3**\nsince, 3 is less than 5, we will swap these.\nAfter swapping:\n**[1,2,4,3,5]**\nNow, we can see that 3 is not at its correct position, so we have to check in the Sorted part as well i.e. **[1,2,4]**\nHere, we will use **tmp** pointer to iterate linked list from the head till that element, and compare that element (here, 3) with all the elements, and position it accordingly.\n\nOnce, we complete the comparing and swapping for all the remaining elements, our resultant list is sorted, which we return.\n\nHere\'s the complete **code** for your reference:\n```\nclass Solution {\npublic:\n ListNode* insertionSortList(ListNode* head) {\n ListNode* prev = nullptr, *curr=head, *tmp=head;\n if(head==nullptr || head->next==nullptr)\n return head;\n else{\n prev = head;\n curr = head->next;\n while(curr!=nullptr){\n if(prev->val > curr->val){\n swap(prev->val, curr->val);\n tmp = head;\n while(tmp!=prev){\n if(tmp->val > prev->val){\n swap(tmp->val, prev->val);\n }\n tmp = tmp->next;\n }\n }\n prev=prev->next;\n curr=curr->next;\n }\n return head;\n }\n }\n};\n```\n\n***PS: Do give it an upvote if this helped.\nIn case of any queries or suggestions feel free to comment below.\nThanks!*** | 7 | 0 | ['C'] | 1 |
insertion-sort-list | [Python] Clean & Concise - Time O(n^2), Space O(1) | python-clean-concise-time-on2-space-o1-b-ifvj | python\nclass Solution(object):\n def insertionSortList(self, head):\n dummyHead= ListNode(0)\n \n def insert(head):\n prev = | hiepit | NORMAL | 2020-11-03T07:19:27.455852+00:00 | 2020-11-03T07:19:27.455903+00:00 | 268 | false | ```python\nclass Solution(object):\n def insertionSortList(self, head):\n dummyHead= ListNode(0)\n \n def insert(head):\n prev = dummyHead\n curr = dummyHead.next\n while curr and curr.val <= head.val:\n prev = curr\n curr = curr.next\n \n prev.next = head\n head.next = curr\n \n while head != None:\n next = head.next\n insert(head)\n head = next\n \n return dummyHead.next\n```\n**Complexity:**\n- Time: `O(N^2)`\n- Space: `O(1)` | 7 | 1 | [] | 1 |
insertion-sort-list | [recommend for beginners]clean C++ implementation with detailed explaination | recommend-for-beginnersclean-c-implement-65ux | This problem is all about details, you just need to check what to do when insert the cur-pointer to the linked-list.\n\nYou need to consider 2 cases carefully. | rainbowsecret | NORMAL | 2016-01-17T15:08:33+00:00 | 2016-01-17T15:08:33+00:00 | 1,454 | false | This problem is all about details, you just need to check what to do when insert the cur-pointer to the linked-list.\n\nYou need to consider 2 cases carefully. I believe it is all about details.\n\n class Solution {\n public:\n ListNode* insertionSortList(ListNode* head) {\n if(!head) return NULL;\n ListNode* dummy=new ListNode(-1);\n dummy->next=head;\n ListNode *cur=head->next, *prev=head;\n while(cur){\n //record the next pointer \n ListNode* nextPtr=cur->next;\n //find the inserted position from the dummy start position\n ListNode *prePtr=dummy;\n ListNode *curPtr=dummy->next;\n while(curPtr!=cur && curPtr->val <= cur->val){\n prePtr=prePtr->next;\n curPtr=curPtr->next;\n }\n /* check the current position */\n /* case 1 : we need to insert it */\n if( curPtr!= cur ){\n prePtr->next = cur;\n cur->next = curPtr;\n prev->next = nextPtr;\n cur=nextPtr;\n }\n /* case 2 : we do not need to insert it */\n else{\n prev=cur;\n cur=cur->next;\n }\n }\n return dummy->next;\n }\n }; | 7 | 1 | [] | 2 |
insertion-sort-list | ✔️ 100% Fastest TypeScript Solution | 100-fastest-typescript-solution-by-serge-xjsj | \n/**\n * Definition for singly-linked list.\n * class ListNode {\n * val: number\n * next: ListNode | null\n * constructor(val?: number, next?: Lis | sergeyleschev | NORMAL | 2022-03-29T05:01:30.562192+00:00 | 2022-03-30T16:41:33.061682+00:00 | 1,118 | false | ```\n/**\n * Definition for singly-linked list.\n * class ListNode {\n * val: number\n * next: ListNode | null\n * constructor(val?: number, next?: ListNode | null) {\n * this.val = (val===undefined ? 0 : val)\n * this.next = (next===undefined ? null : next)\n * }\n * }\n */\n\nfunction insertionSortList(head: ListNode | null): ListNode | null {\n if (!head) return null\n if (!head.next) return head\n\n let output = head\n let curr = head.next\n\n head.next = null\n\n while (curr) {\n const next = curr.next\n const insertion = curr\n\n output = insert(output, insertion)\n curr = next as ListNode\n }\n\n return output\n}\n\nfunction insert(head: ListNode, other: ListNode) {\n let curr = head\n const val = other.val\n\n if (val <= head.val) {\n other.next = head\n return other\n }\n\n while (curr) {\n if ((val > curr.val && curr.next && val <= curr.next.val) || !curr.next) {\n other.next = curr.next\n curr.next = other\n\n return head\n }\n\n curr = curr.next as ListNode\n }\n\n return head\n}\n```\n\nLet me know in comments if you have any doubts. I will be happy to answer.\n\nPlease upvote if you found the solution useful. | 6 | 0 | ['TypeScript', 'JavaScript'] | 0 |
insertion-sort-list | insertion Sort List - 100% | insertion-sort-list-100-by-abhishekjha78-i7wf | class Solution {\n public ListNode insertionSortList(ListNode head) {\n ListNode prev = head;\n ListNode curr = prev.next;\n \n i | abhishekjha786 | NORMAL | 2021-12-15T08:50:45.749703+00:00 | 2021-12-15T08:50:45.749730+00:00 | 165 | false | class Solution {\n public ListNode insertionSortList(ListNode head) {\n ListNode prev = head;\n ListNode curr = prev.next;\n \n if(head==null || head.next==null) \n return head;\n \n while(curr != null) {\n if(curr.val < prev.val) {\n prev.next = curr.next;\n if(curr.val <= head.val) {\n curr.next = head;\n head = curr;\n } else {\n //search starting from the head\n ListNode ptr = head;\n while(ptr.next!=null && ptr.next.val < curr.val)\n ptr = ptr.next;\n ListNode temp = ptr.next;\n ptr.next = curr;\n curr.next = temp;\n }\n curr = prev.next;\n } else {\n curr = curr.next;\n prev = prev.next;\n }\n }\n return head; \n }\n}\n**Please help to UPVOTE if this post is useful for you.\nIf you have any questions, feel free to comment below.\nHAPPY CODING :)\nLOVE CODING :**\n | 6 | 1 | ['Linked List'] | 1 |
insertion-sort-list | C++ | c-by-ahmedmohamedd-5a9o | \n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * | ahmedmohamedd | NORMAL | 2020-11-02T08:54:21.688924+00:00 | 2020-11-02T08:54:21.688971+00:00 | 696 | false | ```\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* insertionSortList(ListNode* head) {\n if(head == nullptr ){\n return nullptr ;\n }\n vector<ListNode*>nodes;\n nodes.push_back(head);\n ListNode*temp = head->next ;\n while(temp != nullptr ){\n nodes.push_back(temp);\n for(int i = nodes.size()-1 ; i > 0 ; i -- ){\n if( nodes[i]->val < nodes[i-1]->val ){\n swap(nodes[i-1]->val , nodes[i]->val); \n }\n else{\n break;\n }\n }\n temp = temp->next;\n }\n return head ;\n }\n};\n``` | 6 | 0 | [] | 3 |
insertion-sort-list | One way to accept in python against TLE | one-way-to-accept-in-python-against-tle-465z9 | My original code is very intuitive. I checked each unsorted element one by one and added it into sorted part. The way I added it is that I check from the head t | ideno | NORMAL | 2014-07-13T05:10:32+00:00 | 2014-07-13T05:10:32+00:00 | 2,654 | false | My original code is very intuitive. I checked each unsorted element one by one and added it into sorted part. The way I added it is that I check from the head to tailer of the sorted part. Here is my original code in python and off-line test for 2000 data costs 2.3s while the result is TLE for on-line test.\n\n class Solution:\n # @param head, a ListNode\n # @return a ListNode\n def insertionSortList(self, head):\n linkHead = ListNode(0)\n linkHead.next = head\n sortedEnd = linkHead.next\n\n if sortedEnd == None:\n return head\n \n while sortedEnd.next != None:\n pointer = sortedEnd.next\n sortedEnd.next = pointer.next\n\n innerPointer = linkHead\n\n while innerPointer != sortedEnd and innerPointer.next.val < pointer.val:\n innerPointer = innerPointer.next\n \n pointer.next = innerPointer.next\n innerPointer.next = pointer\n\n if innerPointer == sortedEnd:\n sortedEnd = pointer\n \n return linkHead.next\n\nThen I change the way to find the insertion spot like this:\nThe off-line test costs 1.7s and it accepted for on-line test\n\n class Solution:\n # @param head, a ListNode\n # @return a ListNode\n def insertionSortList(self, head):\n linkHead = ListNode(0)\n linkHead.next = head\n sortedEnd = linkHead.next\n\n if sortedEnd == None:\n return head\n\n innerPointer = linkHead.next #declare innerPointer here\n\n while sortedEnd.next != None:\n pointer = sortedEnd.next\n sortedEnd.next = pointer.next\n\n # reset innerPointer only when pointer is needed to be inserted before innerPointer\n if innerPointer.val > pointer.val:\n innerPointer = linkHead\n\n while innerPointer != sortedEnd and innerPointer.next.val < pointer.val:\n innerPointer = innerPointer.next\n \n pointer.next = innerPointer.next\n innerPointer.next = pointer\n\n if innerPointer == sortedEnd:\n sortedEnd = pointer\n \n return linkHead.next\n\nThere are some other method to improve performance, e.g. section the linkList and store the value of each segment's front elem, then the process of finding the insertion spot will be more efficient | 6 | 0 | ['Python'] | 3 |
insertion-sort-list | 10 line clean and easy-to-understand C++ solution | 10-line-clean-and-easy-to-understand-c-s-zz9e | Please see [my blog post][1] for more.\n\n ListNode insertionSortList(ListNode head) {\n ListNode dummy(INT_MIN);\n ListNode prev, cur, *next;\ | xiaohui7 | NORMAL | 2015-03-31T15:49:59+00:00 | 2015-03-31T15:49:59+00:00 | 1,104 | false | Please see [my blog post][1] for more.\n\n ListNode *insertionSortList(ListNode *head) {\n ListNode dummy(INT_MIN);\n ListNode *prev, *cur, *next;\n \n for (auto p = head; p; p = next) {\n next = p->next;\n // invariant: list headed by dummy.next is sorted\n for (prev = &dummy, cur = prev->next; cur && p->val > cur->val; prev = cur, cur = cur->next)\n ;\n prev->next = p;\n p->next = cur;\n }\n \n return dummy.next;\n }\n\n [1]: http://xiaohuiliucuriosity.blogspot.com/2015/02/insertion-sort-list.html | 6 | 1 | ['Linked List', 'Sorting'] | 0 |
insertion-sort-list | Maybe the best JAVA solution with code comments | maybe-the-best-java-solution-with-code-c-o7n4 | public class Solution {\n \n public ListNode insertionSortList(ListNode head) {\n if(head == null || head.next == null){\n r | zwangbo | NORMAL | 2015-01-29T06:41:29+00:00 | 2015-01-29T06:41:29+00:00 | 2,363 | false | public class Solution {\n \n public ListNode insertionSortList(ListNode head) {\n if(head == null || head.next == null){\n return head;\n }\n //record node before insertNode\n ListNode preNode = head;\n //rocord node need to be inserted\n ListNode insertNode = head.next;\n \n while(insertNode != null){\n //store next insert node\n ListNode nextInsert = insertNode.next;\n //insert before head\n if(insertNode.val <= head.val){\n preNode.next = insertNode.next;\n insertNode.next = head;\n head = insertNode;\n }\n else if(insertNode.val >= preNode.val){ //insert after tail\n preNode = preNode.next;\n }\n else{ //insert between head and tail\n ListNode compareNode = head;\n //start from the node after head, find insert position\n while(compareNode.next.val < insertNode.val) compareNode = compareNode.next;\n //insert\n preNode.next = insertNode.next;\n insertNode.next = compareNode.next;\n compareNode.next = insertNode;\n }\n //get next insert node\n insertNode = nextInsert;\n }\n return head;\n }\n }\n\nHope it will helpful. The thinking is very straightforward:\n\n 1. Insert before head.\n 2. Insert after tail.(no need change the list).\n 3. Insert between head and tail. | 6 | 1 | ['Java'] | 2 |
insertion-sort-list | 💢☠💫Easiest👾Faster✅💯 Lesser🧠 🎯 C++✅Python3🐍✅Java✅C✅Python🐍✅C#✅💥🔥💫Explained☠💥🔥 Beats 100 | easiestfaster-lesser-cpython3javacpython-2pc8 | Intuition\n\n\n\n\n\n\n\n\njavascript []\n//JavaScript Code\n/**\n * Definition for singly-linked list.\n * function ListNode(val, next) {\n * this.val = (v | Edwards310 | NORMAL | 2024-08-27T16:41:12.469021+00:00 | 2024-08-27T16:41:12.469061+00:00 | 2,270 | false | # Intuition\n\n\n\n\n\n\n\n\n```javascript []\n//JavaScript Code\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} head\n * @return {ListNode}\n */\nvar insertionSortList = function(head) {\n const arr = []\n let curr = head\n while(curr != undefined){\n arr.push(curr.val)\n curr = curr.next\n }\n \n arr.sort((a, b) =>{\n return a - b\n })\n \n //console.log(arr)\n curr = head\n while(curr != undefined){\n curr.val = arr.shift()\n curr = curr.next\n }\n return head\n};\n```\n```C++ []\n//C++ Code\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* insertionSortList(ListNode* head) {\n vector<ListNode*> vec;\n while(head){\n vec.push_back(head);\n head = head->next;\n }\n sort(vec.begin(), vec.end(), [&](ListNode* a, ListNode* b){\n return a->val > b->val;\n });\n \n ListNode* prev = nullptr;\n for(int i = 0; i < vec.size(); i++){\n head = vec[i];\n head->next = prev;\n prev = head;\n }\n return head;\n }\n};\n```\n```Python3 []\n#Python3 Code\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 insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n res = []\n while head:\n res.append(head.val)\n head = head.next\n \n res = sorted(res, reverse = True)\n #print(res)\n dummy = None\n \n for node in res:\n head = ListNode(node)\n head.next = dummy\n dummy = head\n \n return dummy\n \n```\n```Java []\n//Java Code\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 insertionSortList(ListNode head) {\n PriorityQueue<Integer> pq = new PriorityQueue<>();\n ListNode curr = head;\n // Get values to PQueue (insertion sort inside queue)\n while(curr != null){\n pq.add(curr.val);\n curr = curr.next;\n }\n // Fill values into list\n curr = head;\n while(curr != null){\n curr.val = pq.poll();\n curr = curr.next;\n }\n return head;\n }\n}\n```\n```C []\n//C Code\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * struct ListNode *next;\n * };\n */\ntypedef struct ListNode ListNode;\n\nListNode* newNode(int val){\n ListNode* node = (ListNode*)malloc(sizeof(ListNode));\n node->val = val;\n node->next = NULL;\n return node;\n}\nstruct ListNode* insertionSortList(struct ListNode* head) {\n ListNode* dummy = newNode(0);\n dummy -> next = head;\n ListNode *pre = dummy, *cur = head;\n while (cur) {\n if ((cur -> next) && (cur -> next -> val < cur -> val)) {\n while ((pre -> next) && (pre -> next -> val < cur -> next -> val)) {\n pre = pre -> next;\n }\n ListNode* temp = pre -> next;\n pre -> next = cur -> next;\n cur -> next = cur -> next -> next;\n pre -> next -> next = temp;\n pre = dummy;\n }\n else\n cur = cur -> next;\n }\n return dummy -> next;\n}\n```\n```Python []\n#Python Code\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 insertionSortList(self, head):\n """\n :type head: ListNode\n :rtype: ListNode\n """\n result = ListNode(-5000)\n\n def insert(partial, toplace):\n initial = partial\n partial = partial.next\n while partial != None:\n if toplace < partial.val:\n break\n initial = partial\n partial = partial.next\n newnode = ListNode(toplace)\n initial.next = newnode\n newnode.next = partial\n\n\n while head != None:\n insert(result, head.val)\n head = head.next\n\n result = result.next\n return result\n```\n```C# []\n//C# Code\n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * public int val;\n * public ListNode next;\n * public ListNode(int val=0, ListNode next=null) {\n * this.val = val;\n * this.next = next;\n * }\n * }\n */\npublic class Solution {\n public ListNode InsertionSortList(ListNode head) {\n for(ListNode cur = head; cur != null; cur = cur.next){\n for(ListNode j = head; j != cur; j = j.next){\n if(j.val > cur.val){\n int x = j.val;\n j.val = cur.val;\n cur.val = x;\n }\n }\n }\n return head;\n }\n}\n```\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 O(N * logN)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(N)\n# Code\n\n | 5 | 1 | ['Linked List', 'C', 'Sorting', 'Python', 'C++', 'Java', 'Python3', 'JavaScript', 'C#'] | 5 |
insertion-sort-list | using Bubble sort in C | using-bubble-sort-in-c-by-shaik_moinuddi-x3zd | Intuition\njust use the bubble sort.the only difference is u need to reset the pointer to point head after the completation of second loop and in second loop u | Shaik_Moinuddin73 | NORMAL | 2023-07-12T14:50:55.688681+00:00 | 2023-08-12T14:42:15.363946+00:00 | 808 | false | # Intuition\njust use the bubble sort.the only difference is u need to reset the pointer to point head after the completation of second loop and in second loop u need to swap two values if one val is greater than another.then update temp pointer to its next\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(1)\n# Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * struct ListNode *next;\n * };\n */\n void swap(struct ListNode *p1,struct ListNode *p2)\n {\n int t=p1->val;\n p1->val=p2->val;\n p2->val=t;\n }\n int len(struct ListNode *head)\n {\n struct ListNode *p=head;\n int l=0;\n while(p!=NULL)\n {\n l++;\n p=p->next;\n }\n return l;\n }\nstruct ListNode* insertionSortList(struct ListNode* head){\n struct ListNode *p=head;\n int i,j;\n int l=len(head);\n for(i=0;i<l;i++)\n {\n for(j=0;j<l-i-1;j++)\n {\n if(p->val>p->next->val)\n {\n swap(p,p->next);\n }\n p=p->next;\n }\n p=head;\n }\n return head;\n\n}\n``` | 5 | 0 | ['Linked List', 'C', 'Sorting'] | 2 |
insertion-sort-list | Simple Solution || O(N^2) time || O(1) space | simple-solution-on2-time-o1-space-by-shr-1jzx | \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(nullpt | Shristha | NORMAL | 2023-01-28T11:51:12.885065+00:00 | 2023-01-28T11:51:12.885099+00:00 | 680 | false | \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* insertionSortList(ListNode* head) {\n // idea is we maintain a prev list & for each node we check in prev list until all elements are smaller then insert the node between the smaller & greater elements.\n if(!head || !head->next)return head;\n ListNode* dummy=new ListNode(INT_MIN);\n ListNode* tail=dummy;\n ListNode* curr=head;\n while(curr){\n ListNode * next=curr->next;\n while(tail->next && tail->next->val<curr->val){\n tail=tail->next;\n }\n curr->next=tail->next;\n tail->next=curr;\n tail=dummy;\n curr=next;\n }\n return dummy->next;\n \n }\n};\n``` | 5 | 0 | ['Sorting', 'C++'] | 0 |
insertion-sort-list | simple c++ clean solution | simple-c-clean-solution-by-dhiraj121-fsos | class Solution {\npublic:\n\n ListNode insertionSortList(ListNode head) {\n ListNode nxt = head -> next;\n while(nxt != NULL)\n {\n | Dhiraj121 | NORMAL | 2022-08-30T04:55:58.369157+00:00 | 2022-08-30T04:55:58.369184+00:00 | 942 | false | class Solution {\npublic:\n\n ListNode* insertionSortList(ListNode* head) {\n ListNode *nxt = head -> next;\n while(nxt != NULL)\n {\n ListNode *curr = head;\n while(curr != nxt)\n {\n if(nxt -> val < curr -> val)\n swap(curr -> val, nxt -> val);\n \n curr = curr -> next;\n }\n nxt = nxt -> next; \n }\n return head;\n }\n}; | 5 | 0 | ['Linked List', 'C'] | 2 |
insertion-sort-list | C++ | In-Place Insertion Sort | c-in-place-insertion-sort-by-apartida-mx7b | I sorted the given list in-place since the problem didn\'t specify producing a new list.\n```\n ListNode insertionSortList(ListNode head) {\n \n | apartida | NORMAL | 2021-12-15T20:11:14.082223+00:00 | 2021-12-15T20:11:14.082279+00:00 | 378 | false | I sorted the given list in-place since the problem didn\'t specify producing a new list.\n```\n ListNode* insertionSortList(ListNode* head) {\n \n /* Base case */\n if (head == nullptr) return nullptr; \n \n /* Perform in-place insertion sort. */\n /* Time - O(n^2); Space - O(1) */\n int temp = 0;\n for (ListNode* node = head; node != nullptr; node = node->next) { \n for (ListNode* comp = head; comp != node; comp = comp->next) {\n /* If the current value is less than a previous value, */\n /* then swap the values. */\n if (node->val < comp->val) {\n temp = node->val;\n node->val = comp->val;\n comp->val = temp;\n }\n }\n }\n\n return head;\n } | 5 | 0 | ['C'] | 1 |
insertion-sort-list | Python Solution Explained (video + code) | python-solution-explained-video-code-by-wtoia | \nhttps://www.youtube.com/watch?v=-0w2uswTST8\n\nclass Solution:\n def insertionSortList(self, head: ListNode) -> ListNode:\n dummy_head = ListNode()\ | spec_he123 | NORMAL | 2020-11-02T17:48:46.952719+00:00 | 2020-11-02T17:48:46.952752+00:00 | 509 | false | [](https://www.youtube.com/watch?v=-0w2uswTST8)\nhttps://www.youtube.com/watch?v=-0w2uswTST8\n```\nclass Solution:\n def insertionSortList(self, head: ListNode) -> ListNode:\n dummy_head = ListNode()\n curr = head\n \n while curr:\n prev_pointer = dummy_head\n next_pointer = dummy_head.next\n \n while next_pointer:\n if curr.val < next_pointer.val:\n break\n prev_pointer = prev_pointer.next\n next_pointer = next_pointer.next\n \n temp = curr.next\n \n curr.next = next_pointer\n prev_pointer.next = curr\n \n curr = temp\n \n return dummy_head.next\n``` | 5 | 0 | ['Linked List', 'Python', 'Python3'] | 0 |
insertion-sort-list | A short and clear c++ solution. | a-short-and-clear-c-solution-by-dikea-1vkg | c++\nclass Solution {\npublic:\n ListNode* insertionSortList(ListNode* head) {\n if(!head) return NULL;\n ListNode *res = new ListNode(0);\n | dikea | NORMAL | 2019-07-06T13:29:04.036146+00:00 | 2019-07-06T13:29:18.470559+00:00 | 188 | false | ```c++\nclass Solution {\npublic:\n ListNode* insertionSortList(ListNode* head) {\n if(!head) return NULL;\n ListNode *res = new ListNode(0);\n while(head) {\n ListNode* p = res->next;\n ListNode* pre = res;\n while(p && head->val > p->val) {\n pre = p;\n p = p->next;\n }\n pre->next = new ListNode(head->val);\n pre = pre->next;\n pre->next = p;\n head = head->next;\n }\n return res->next;\n }\n};\n``` | 5 | 0 | [] | 0 |
insertion-sort-list | Solution in C | solution-in-c-by-joshua_duan-a2kz | Code\n\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * struct ListNode *next;\n * };\n */\nstruct ListNode* insertion | joshua_duan | NORMAL | 2024-03-21T06:14:47.381692+00:00 | 2024-03-21T06:14:47.381723+00:00 | 693 | false | # Code\n```\n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * struct ListNode *next;\n * };\n */\nstruct ListNode* insertionSortList(struct ListNode* head) {\n if (!head || !head->next) {\n return head;\n }\n\n struct ListNode* dummy = malloc(sizeof(struct ListNode));\n dummy->next = head;\n\n struct ListNode* prev = head;\n struct ListNode* cur = head->next;\n\n while (cur) {\n // already in-order\n if (prev->val <= cur->val) {\n prev = cur;\n cur = cur->next;\n } else {\n struct ListNode* temp = dummy;\n \n while(cur->val > temp->next->val) \n temp = temp->next;\n\n // find the stop\n prev->next = cur->next;\n cur->next = temp->next;\n temp->next = cur;\n\n cur = prev->next;\n }\n }\n return dummy->next;\n}\n``` | 4 | 0 | ['C'] | 1 |
insertion-sort-list | Insertion Sort || JAVA Easy Solution | insertion-sort-java-easy-solution-by-saa-usok | Explanation:\n\n1. Initialization:\n - A dummy node is created at the beginning to simplify the insertion process. The dummy node\'s next points to the sorted | saad_hussain_ | NORMAL | 2024-02-29T18:35:57.466463+00:00 | 2024-02-29T18:35:57.466484+00:00 | 744 | false | ### Explanation:\n\n1. **Initialization:**\n - A dummy node is created at the beginning to simplify the insertion process. The dummy node\'s `next` points to the sorted list.\n - `current` is a pointer initialized to the head of the original linked list.\n\n2. **Iterative Sorting:**\n - The algorithm iterates through the original linked list (`while(current!=null)`).\n - Inside the loop:\n - `next` is used to keep track of the next node in the original list before modification.\n - The `insert_at_pos` method is called to insert the current node at the correct position in the sorted list.\n\n3. **Insertion at Position:**\n - The `insert_at_pos` method takes the dummy node and the current node to be inserted.\n - It traverses the sorted list until it finds the correct position where the current node should be inserted.\n - The insertion is done by updating the `next` pointers accordingly.\n\n4. **Return:**\n - The sorted linked list starts from the `dummy.next`, so the method returns `dummy.next`.\n\n### Time Complexity:\n- The outer loop iterates through each node in the original linked list once, making it O(n), where n is the number of nodes.\n- The inner `insert_at_pos` method takes O(n) in the worst case (inserting at the end of the sorted list).\n\nHence, the overall time complexity is O(n^2).\n\n### Space Complexity:\n- The algorithm uses a constant amount of extra space regardless of the input size (dummy node and a few pointers), making it O(1).\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 insertionSortList(ListNode head) {\n if(head==null || head.next==null){\n return head;\n }\n\n ListNode dummy=new ListNode(0);\n ListNode current=head;\n\n while(current!=null){\n ListNode next=current.next;\n insert_at_pos(dummy,current);\n current=next;\n }\n \n return dummy.next;\n\n }\n\n private void insert_at_pos(ListNode dummy,ListNode node){\n ListNode current=dummy;\n\n while(current.next!=null && current.next.val<node.val){\n current=current.next;//move this many numbers to get the proper position\n }\n\n node.next=current.next;\n current.next=node;\n }\n}\n``` | 4 | 0 | ['Linked List', 'Java'] | 0 |
insertion-sort-list | Easy Solution || Beats 96.63% of users with C++ | easy-solution-beats-9663-of-users-with-c-ohs9 | Upvote\n\n# Code\n\n\nclass Solution {\npublic:\n ListNode* insertionSortList(ListNode* head) {\n vector<int>v;\n while(head!=NULL){\n | 007anshuyadav | NORMAL | 2024-01-21T08:53:03.531168+00:00 | 2024-01-21T08:53:03.531199+00:00 | 766 | false | # Upvote\n\n# Code\n```\n\nclass Solution {\npublic:\n ListNode* insertionSortList(ListNode* head) {\n vector<int>v;\n while(head!=NULL){\n v.push_back(head->val);\n head=head->next;\n\n }\n sort(v.begin(),v.end());\n ListNode* temp=new ListNode(0);\n ListNode* temp1=NULL;\n for(int i=v.size()-1;i>=0;i--){\n temp=new ListNode(v[i]);\n temp->next=temp1;\n temp1=temp;\n }\n return temp1;\n }\n};\n``` | 4 | 0 | ['Linked List', 'Sorting', 'C++'] | 3 |
insertion-sort-list | Exact similar code to insertion sort in the array easy to understand | exact-similar-code-to-insertion-sort-in-0um7p | I request you dry run once on the first exapmle itself and you will understand \njust igonre the cout<val;\n\n# Complexity\n- Time complexity:\nO(N^2)\n\n- Spac | akshansh_ | NORMAL | 2024-01-13T16:19:08.264383+00:00 | 2024-01-13T16:19:08.264413+00:00 | 523 | false | I request you dry run once on the first exapmle itself and you will understand \njust igonre the cout<<head->val;\n\n# Complexity\n- Time complexity:\nO(N^2)\n\n- Space complexity:\nO(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* insertionSortList(ListNode* head) \n {\n if(head==NULL || head->next==NULL)return head;\n ListNode *start=head;\n while(start!=NULL)\n {\n ListNode*temp=head;\n while(temp!=start)\n {\n if(temp->val > start->val)\n {\n swap(temp->val,start->val);\n }\n temp=temp->next;\n }\n cout<<head->val<<" ";\n start=start->next;\n }\n return head;\n \n }\n};\n``` | 4 | 0 | ['C++'] | 2 |
insertion-sort-list | Clearest Go Solution | clearest-go-solution-by-evleria-w3i5 | Github link\n\n\nfunc insertionSortList(head *ListNode) *ListNode {\n\tdummy := new(ListNode)\n\tfor head != nil {\n\t\tcur := dummy\n\t\tfor ; cur.Next != nil | evleria | NORMAL | 2021-12-15T19:33:04.237157+00:00 | 2021-12-15T19:33:04.237192+00:00 | 449 | false | [Github link](https://github.com/evleria/leetcode-in-go/blob/main/problems/0147-insertion-sort-list/insertion_sort_list.go)\n\n```\nfunc insertionSortList(head *ListNode) *ListNode {\n\tdummy := new(ListNode)\n\tfor head != nil {\n\t\tcur := dummy\n\t\tfor ; cur.Next != nil && cur.Next.Val < head.Val; cur = cur.Next {\n\t\t}\n\t\tcur.Next, head.Next, head = head, cur.Next, head.Next\n\t}\n\treturn dummy.Next\n}\n``` | 4 | 0 | ['Go'] | 1 |
insertion-sort-list | 2 Implementation | Explained | 2-implementation-explained-by-sunny_38-qzx1 | Idea?\n We need to sort the list using Insertion Sort.\n Insertion Sort works in O(n^2) time, each time picking up the new element and inserting back this eleme | sunny_38 | NORMAL | 2021-12-15T05:59:28.258192+00:00 | 2021-12-15T06:01:58.659300+00:00 | 214 | false | **Idea?**\n* We need to sort the list using Insertion Sort.\n* Insertion Sort works in **O(n^2) time**, each time picking up the new element and **inserting back this element** at the correct position in the sorted list found till now.\n\n**Implementation 1:-(Not Efficient)**\n* Each time when we pick up the new element, we need to **traverse in a backward manner** in the sorted list to insert this element at the correct position right?\n* How do we traverse in a backward manner?\n* We will be **reversing the sorted list up to the current node**.\n* Then, we\'ll insert this new value at the correct position.\n* Again **restore the original list by reversing again**.\n\n```\nclass Solution {\npublic:\n // Time Complexity:- O(n^2)\n // Space Complexity:- O(1)\n // reverse the List upto the given node\n void reverseList(ListNode* head,ListNode* upto){\n ListNode *prev = NULL;\n while(head!=upto){\n ListNode* temp = head->next;\n head->next = prev;\n prev = head;\n head = temp;\n }\n }\n // insert the value at correct position\n void InsertValue(ListNode* curr){\n ListNode *nxt = curr->next;\n while(nxt!=nullptr and nxt->val>curr->val){\n swap(nxt->val,curr->val);\n nxt = nxt->next;\n curr = curr->next;\n }\n }\n ListNode* insertionSortList(ListNode* head) {\n ListNode* curr = head;\n while(curr!=nullptr){\n ListNode* temp = curr->next;\n reverseList(head,curr->next); // reverse the list prior to this node\n InsertValue(curr); // insert the value\n reverseList(curr,nullptr); // reverse the previous list again\n curr->next = temp;\n curr = curr->next;\n }\n return head;\n }\n};\n```\n\n**Implementation 2:-(Efficient)**\n* The above implementation is quite a hectic task, Can we improve it? **Can we insert a dummy node**?\n* Okay, Let\'s make a dummy node.\n* Each time when we encounter a new element, we\'ll find the correct position from the start of the sorted list(*starting from dummy node*) and find the position where this new value should be inserted.\n* **Note:- Here we aren\'t reversing any list here.**\n\n```\nclass Solution {\npublic:\n // Time Complexity:- O(n^2)\n // Space Complexity:- O(1)\n ListNode* insertionSortList(ListNode* head) {\n ListNode* dummy = new ListNode(-5005);\n ListNode* curr = head;\n while(curr!=nullptr){\n ListNode* nxt = curr->next; // store next node for iteration\n ListNode* iter = dummy;\n // iterate from the beginning and find the suitable position of curr->val\n while(iter->next!=nullptr and iter->next->val<curr->val)\n iter = iter->next;\n curr->next = iter->next;\n iter->next = curr; // insert node at this position\n curr = nxt;\n }\n return dummy->next;\n }\n};\n```\n**Don\'t Forget to Upvote!**\n | 4 | 0 | [] | 0 |
insertion-sort-list | Java two solutions - Pointer change and Value change | java-two-solutions-pointer-change-and-va-v8kn | Pointer change\n\nclass Solution {\n public ListNode insertionSortList(ListNode head) {\n ListNode dummy = new ListNode(0);\n ListNode curr | vinsinin | NORMAL | 2020-12-31T21:32:43.679149+00:00 | 2020-12-31T21:32:43.679195+00:00 | 387 | false | **Pointer change**\n```\nclass Solution {\n public ListNode insertionSortList(ListNode head) {\n ListNode dummy = new ListNode(0);\n ListNode curr = head;\n \n while (curr != null){\n ListNode prev = dummy;\n \n while (prev.next != null && prev.next.val < curr.val)\n prev = prev.next;\n \n ListNode next = curr.next;\n curr.next = prev.next;\n prev.next = curr;\n curr = next;\n }\n \n return dummy.next;\n }\n}\n```\n**Value change**\n```\n class Solution {\n public ListNode insertionSortList(ListNode head) {\n ListNode cur = head;\n while(cur != null) { \n ListNode start = head;\n\t\t\t\n\t\t\t// move to the position in the sorted part\n while(start.val < cur.val && start != cur)\n start = start.next;\n \n while(start != cur.next) {\n //swap value with current element\n int tmp = start.val;\n start.val = cur.val;\n cur.val = tmp;\n \n start = start.next;\n } \n cur = cur.next; \n } \n return head; \n }\n }\n``` | 4 | 0 | ['Java'] | 1 |
insertion-sort-list | [Java] JAVA 8 STREAM API | java-java-8-stream-api-by-kostrych_artem-u3ah | \nclass Solution {\n public ListNode insertionSortList(ListNode head) {\n\t\tList<ListNode> listNodes = new LinkedList<>();\n\t\twhile (head!=null)\n\t\t{\n\ | kostrych_artem | NORMAL | 2020-11-02T08:00:26.540932+00:00 | 2020-11-02T08:00:26.540980+00:00 | 144 | false | ```\nclass Solution {\n public ListNode insertionSortList(ListNode head) {\n\t\tList<ListNode> listNodes = new LinkedList<>();\n\t\twhile (head!=null)\n\t\t{\n\t\t\tlistNodes.add(head);\n\t\t\thead=head.next;\n\t\t}\n\t\tlistNodes=listNodes.stream().sorted(Comparator.comparingInt(node -> node.val)).collect(Collectors.toList());\n\t\tfor (int i = 0; i < listNodes.size()-1; i++)\n\t\t{\n\t\t\tlistNodes.get(i).next=listNodes.get(i+1);\n\t\t\tlistNodes.get(i+1).next=null;\n\t\t}\n\t\treturn listNodes.stream().findFirst().orElse(null);\n\t}\n}\n``` | 4 | 1 | [] | 0 |
insertion-sort-list | Python3 & Java 4 pointers solution | python3-java-4-pointers-solution-by-meiy-0f7g | \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\ncl | meiyaowen | NORMAL | 2020-08-20T01:20:03.144762+00:00 | 2020-08-20T01:52:11.709120+00:00 | 440 | false | ```\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 insertionSortList(self, head: ListNode) -> ListNode:\n # if head is empty or only have 1 element, return head\n if not head: return None\n if not head.next: return head\n \n # Need four pointers and we are going to sort right at the same place\n # define dummy to hold the begining of the sorted list,\n # define temp to hold a value if order need to be changed\n # define current to loop over the list to be sorted\n # define runner to loop over the sorted linklist from dummy ->-> current\n \n dummy = ListNode(None,head)\n current = head\n \n while current.next is not None:\n # if in-order, move to the next number\n if current.next.val >= current.val:\n current = current.next\n \n # if current.next.val < current.val, list is not in-order, \n # we need to remove the current number from the origional linklist, \n # then do insertion from dummy.next \n else: \n temp = current.next\n runner = dummy\n current.next = current.next.next\n \n # insert the value in the sorted linklist\n while runner.next.val <= temp.val:\n runner = runner.next\n runner.next, temp.next = temp, runner.next\n \n return dummy.next \n \n \n \n \n \n```\n\n\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 insertionSortList(ListNode head) {\n // if head.size is samller than 2, we can just return head\n if(head==null || head.next ==null) return head;\n \n // use current to go thourgh the linklist\n\t\t // use temp to store the not-in-order element\n\t\t // use runner to loop over the sorted linklist\n\t\t \n ListNode dummy = new ListNode(-1,head);\n ListNode current = head;\n ListNode temp = null;\n ListNode runner = null;\n \n while (current.next!=null){\n // if current.next bigger than current, we do not need to change the order\n if (current.next.val >= current.val){\n current = current.next;\n }else{\n runner = dummy;\n temp = current.next; // save the not in-order element to temp\n current.next = current.next.next;//remove the not in-order element from the list\n \n // use runner, looping from dummy, to find where to insert temp\n while (runner.next.val <= temp.val){\n runner = runner.next;\n }\n // find the place to insert, re-build the sorted link-list \n temp.next = runner.next;\n runner.next = temp;\n }\n }\n return dummy.next;\n }\n}\n``` | 4 | 0 | ['Java', 'Python3'] | 1 |
insertion-sort-list | [Rust] | rust-by-qini8-6ccs | \nimpl Solution {\n pub fn insertion_sort_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {\n let mut head = head;\n let mut new_hea | qini8 | NORMAL | 2019-12-15T08:27:08.717456+00:00 | 2019-12-15T08:27:08.717501+00:00 | 136 | false | ```\nimpl Solution {\n pub fn insertion_sort_list(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {\n let mut head = head;\n let mut new_head = ListNode::new(0);\n while let Some(mut boxed) = head.take() {\n head = boxed.next.take();\n let mut ptr = &mut new_head;\n // ptr.next should be the first element bigger than or equal to boxed.val or None.\n while ptr.next.as_ref().is_some() && ptr.next.as_ref().unwrap().val < boxed.val {\n ptr = ptr.next.as_mut().unwrap();\n }\n boxed.next = ptr.next.take();\n ptr.next = Some(boxed);\n }\n new_head.next\n }\n}\n``` | 4 | 0 | [] | 2 |
insertion-sort-list | [[[ C++ ]]] Top 80% O(N) With O(1) Memory - Slick Rick Solution [[KoDerZ KamP]] | c-top-80-on-with-o1-memory-slick-rick-so-lv8j | \nclass Solution {\npublic:\n ListNode* insertionSortList(ListNode* head) {\n \n //We will store the solution after sentinel..\n ListNod | nraptis | NORMAL | 2019-07-06T02:39:07.860722+00:00 | 2019-07-06T02:39:07.860753+00:00 | 123 | false | ```\nclass Solution {\npublic:\n ListNode* insertionSortList(ListNode* head) {\n \n //We will store the solution after sentinel..\n ListNode *aSentinel = new ListNode(0);\n ListNode *aPrev = NULL;\n \n //We pluck nodes out from the original list, one at a time.\n ListNode *aInsert = head;\n ListNode *aNextInsert = NULL;\n \n //We search through the sorted partial result.\n ListNode *aSearch = NULL;\n \n while (aInsert) {\n \n //a begin\n aNextInsert = aInsert->next;\n \n //Find the spot to insert the node...\n \n aPrev = aSentinel;\n aSearch = aSentinel->next;\n while (aSearch != NULL && aSearch->val < aInsert->val) {\n aPrev = aSearch;\n aSearch = aSearch->next;\n }\n \n aPrev->next = aInsert;\n aInsert->next = aSearch;\n \n //a end\n aInsert = aNextInsert;\n }\n \n ListNode *aResult = aSentinel->next;\n delete aSentinel;\n return aResult;\n }\n};\n```\n\nWe keep the code short by using a sentinel node. | 4 | 0 | [] | 0 |
insertion-sort-list | 3 ms Java solution without recursive | 3-ms-java-solution-without-recursive-by-0ulez | public ListNode insertionSortList(ListNode head) {\n \n\t\tif(head == null || head.next == null) {\n return head;\n } \n Li | swetchha | NORMAL | 2019-04-04T17:09:40.414620+00:00 | 2019-04-04T17:09:40.414743+00:00 | 232 | false | public ListNode insertionSortList(ListNode head) {\n \n\t\tif(head == null || head.next == null) {\n return head;\n } \n ListNode newHead = new ListNode(0);\n newHead.next = head;\n \n while(head.next != null) {\n if (head.val > head.next.val) {\n ListNode curr = head.next;\n ListNode prev = newHead;\n while(prev.next.val < curr.val) {\n prev = prev.next;\n }\n head.next = curr.next;\n curr.next = prev.next;\n prev.next = curr;\n } \n else {\n head = head.next;\n }\n } \n return newHead.next;\n } | 4 | 0 | [] | 0 |
insertion-sort-list | Share my C++ solution | share-my-c-solution-by-yunhua-iwbx | It is quite easy if you swap value instead of pointer. check my insertionSortListV. Once you understand the "swap by value" version. then "swap by pointer" is e | yunhua | NORMAL | 2014-09-26T03:04:35+00:00 | 2014-09-26T03:04:35+00:00 | 1,421 | false | It is quite easy if you swap value instead of pointer. check my insertionSortListV. Once you understand the "swap by value" version. then "swap by pointer" is easy too. check insertionSortListP.\n\n1. pi means pre-i. like this: A1->A2->pj->j->A5->A6-pi->i->... the 3 steps to swap i and j by pointer \n\n SWAP(pi->next, pj->next, t);\n SWAP(i->next, j->next, t);\n SWAP(i, j, t);\n\nif J is the head, there is no pj. in order to handle this special case normally. I set up an ListNode object in the stack, called hd. let pj->hd, hd->next = j. \n\n #define SWAP(a, b, t) {t = a; a = b; b = t;}\n class Solution {\n public:\n ListNode *insertionSortListV(ListNode *head) {\n ListNode *i, *j;\n int v;\n \n for (i = head->next; i; i = i->next) {\n for (j = head; j != i; j = j->next) {\n if (i->val < j->val)\n SWAP(i->val, j->val, v);\n }\n }\n return head;\n }\n \n ListNode *insertionSortListP(ListNode *head) {\n ListNode hd(0);\n ListNode *i, *j, *t, *pi, *pj;\n \n i = head->next;\n j = head;\n hd.next = head;\n pi = head;\n pj = &hd;\n while (i) {\n while (j != i) {\n if (i->val < j->val) {\n SWAP(pi->next, pj->next, t);\n SWAP(i->next, j->next, t);\n SWAP(i, j, t);\n }\n pj = j;\n j = j->next;\n }\n j = hd.next;\n pj = &hd;\n pi = i;\n i = i->next;\n }\n return hd.next;\n \n }\n ListNode *insertionSortList(ListNode *head) {\n // 0 or 1 element, no need to sort.\n if (!head || !head->next)\n return head;\n #if 0\n return insertionSortListV(head);\n #else\n return insertionSortListP(head);\n #endif\n }\n }; | 4 | 1 | [] | 2 |
insertion-sort-list | Java iterative and recursive solutions. | java-iterative-and-recursive-solutions-b-wq07 | \n // iteratively\n public ListNode insertionSortList(ListNode head) {\n if (head == null || head.next == null) {\n return head;\n | oldcodingfarmer | NORMAL | 2016-05-01T06:49:53+00:00 | 2016-05-01T06:49:53+00:00 | 709 | false | \n // iteratively\n public ListNode insertionSortList(ListNode head) {\n if (head == null || head.next == null) {\n return head;\n }\n ListNode p, dummy = new ListNode(0), node = head;\n dummy.next = head;\n while (node.next != null) {\n if (node.val > node.next.val) {\n p = dummy;\n while (p.next != null && p.next.val < node.next.val) {\n p = p.next;\n }\n ListNode nxt = node.next.next;\n node.next.next = p.next;\n p.next = node.next;\n node.next = nxt;\n } else { // already sorted\n node = node.next;\n }\n }\n return dummy.next;\n }\n \n // recursively\n public ListNode insertionSortList1(ListNode head) {\n if (head == null || head.next == null) {\n return head;\n }\n ListNode p = insertionSortList(head.next);\n if (head.val <= p.val) { // already sorted\n head.next = p;\n return head;\n }\n ListNode ret = p;\n while (p.next != null && p.next.val < head.val) {\n p = p.next;\n }\n head.next = p.next;\n p.next = head;\n return ret;\n } | 4 | 0 | ['Recursion', 'Iterator', 'Java'] | 1 |
insertion-sort-list | simple python solution | simple-python-solution-by-pengshuang-9mde | '''\nclass Solution(object):\n \n def insertionSortList(self, head):\n """\n :type head: ListNode\n :rtype: ListNode\n """\n | pengshuang | NORMAL | 2016-09-03T01:36:43.513000+00:00 | 2016-09-03T01:36:43.513000+00:00 | 608 | false | '''\nclass Solution(object):\n \n def insertionSortList(self, head):\n """\n :type head: ListNode\n :rtype: ListNode\n """\n if not head:\n return head\n dummy = ListNode(0)\n dummy.next = head\n curr = head\n while curr.next:\n if curr.next.val < curr.val:\n pre = dummy\n while pre.next.val < curr.next.val:\n pre = pre.next\n tmp = curr.next\n curr.next = tmp.next\n tmp.next = pre.next\n pre.next = tmp\n \n else:\n curr = curr.next\n return dummy.next\n''' | 4 | 0 | [] | 0 |
insertion-sort-list | Clear JavaScript solution | clear-javascript-solution-by-loctn-qurx | \nvar insertionSortList = function(head) {\n if (!head) return null;\n let sorted = head;\n head = head.next;\n sorted.next = null;\n while (head | loctn | NORMAL | 2017-03-26T19:04:40.253000+00:00 | 2017-03-26T19:04:40.253000+00:00 | 1,222 | false | ```\nvar insertionSortList = function(head) {\n if (!head) return null;\n let sorted = head;\n head = head.next;\n sorted.next = null;\n while (head) {\n let prev = null;\n let node = sorted;\n while (node && head.val > node.val) {\n prev = node;\n node = node.next;\n }\n let insert = head;\n head = head.next;\n insert.next = node;\n if (prev) {\n prev.next = insert;\n } else {\n sorted = insert;\n }\n }\n return sorted;\n};\n``` | 4 | 0 | ['JavaScript'] | 0 |
insertion-sort-list | CPP || best in the world | cpp-best-in-the-world-by-apoorvjain7222-l7yl | Complexity\n- Time complexity:O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(n)\n Add your space complexity here, e.g. O(n) \n\n# Code | apoorvjain7222 | NORMAL | 2024-10-14T18:33:53.385305+00:00 | 2024-10-14T18:33:53.385333+00:00 | 684 | false | # Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\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* insertionSortList(ListNode* head) {\n vector<int>v;\n ListNode *p = head;\n while(p!=nullptr){\n v.push_back(p->val);\n p=p->next;\n }\n sort(v.begin(),v.end());\n p = head;\n for(int i=0;i<v.size();i++){\n p->val = v[i];\n p=p->next;\n }\n return head;\n }\n};\n``` | 3 | 0 | ['Linked List', 'Sorting', 'C++'] | 1 |
insertion-sort-list | Beginner Friendly using sorting in o(1) space | beginner-friendly-using-sorting-in-o1-sp-ci9t | \n# Approach\nCreating a new linkedlist using insertion sotr\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n\n/**\n * Definit | Aman_8808_Singh | NORMAL | 2024-01-11T09:31:06.656418+00:00 | 2024-01-11T09:33:31.999979+00:00 | 813 | false | \n# Approach\nCreating a new linkedlist using insertion sotr\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(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* insertionSortList(ListNode* head) {\n ListNode* ptr=head;\n ListNode *nh=NULL;\n ListNode *f=NULL;\n while(ptr!=NULL){\n f=ptr->next;\n ptr->next=NULL;\n if(nh==NULL){\n nh=ptr;\n }\n else{\n if(nh->val>ptr->val){\n ptr->next=nh;\n nh=ptr;\n }\n else{\n ListNode *tem=nh;\n while(tem->next!=NULL && tem->next->val<ptr->val){\n tem=tem->next;\n }\n if(tem->next!=NULL){\n ptr->next=tem->next;\n tem->next=ptr;\n }\n else{\n tem->next=ptr;\n }\n }\n }\n ptr=f;\n }\n return nh;\n }\n};\n``` | 3 | 0 | ['Linked List', 'C++'] | 0 |
insertion-sort-list | Simple Java Solution True Insertion Sort | simple-java-solution-true-insertion-sort-5lgu | Intuition\nSplit into two lists. Take from unsorted list and insert into sorted list.\n\n# Approach\nSame as intuition \xAF\\(\u30C4)/\xAF\n\n# Complexity\n- Ti | SnowmanTheCold | NORMAL | 2023-08-25T07:31:31.479751+00:00 | 2023-08-25T17:20:18.260754+00:00 | 815 | false | # Intuition\nSplit into two lists. Take from unsorted list and insert into sorted list.\n\n# Approach\nSame as intuition \xAF\\\\_(\u30C4)_/\xAF\n\n# Complexity\n- Time complexity: O(n^2)\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 insertionSortList(ListNode head) {\n ListNode curr = head.next;\n ListNode h = head; \n h.next = null;\n while (curr != null) {\n ListNode temp = curr;\n curr = curr.next;\n ListNode px = null;\n ListNode x = h;\n while (x != null && x.val < temp.val) {\n px = x;\n x = x.next;\n }\n if (px != null) \n px.next = temp;\n else \n h = temp;\n temp.next = x;\n }\n return h;\n }\n}\n``` | 3 | 0 | ['Java'] | 1 |
insertion-sort-list | C++ | Insertion sort | Easy Solution | c-insertion-sort-easy-solution-by-deepak-byk8 | \n# Complexity\n- Time complexity:O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(n)\n Add your space complexity here, e.g. O(n) \n\n# | godmode_2311 | NORMAL | 2023-03-15T17:34:16.650005+00:00 | 2023-03-15T17:34:16.650051+00:00 | 1,469 | false | \n# Complexity\n- Time complexity:`O(n)`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:`O(n)`\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n ListNode* insertionSortList(ListNode* head) {\n \n // if list contains only one node\n if(!head->next) return head;\n\n // dummy node for sorted list & pointer at dummy list\n ListNode* sorted = new ListNode();\n ListNode* ptr = sorted; // tail\n\n // create first node of sorted list using first node of head\n ptr->next = new ListNode(head->val);\n ptr = ptr->next; // update ptr(tail)\n\n // updating head of input list\n head = head->next;\n\n while(head){\n // if current node\'s value is greater than last node of sorted list\n // need to update tail(ptr) \n if(head->val > ptr->val){\n ptr->next = new ListNode(head->val);\n ptr = ptr->next;\n }\n else{\n // otherwise insert node according to value\n ListNode* pre = sorted;\n ListNode* curr = sorted->next;\n\n while(curr){\n if(curr->val >= head->val){\n pre->next = new ListNode(head->val);\n pre->next->next = curr;\n break;\n }\n pre = curr;\n curr = curr->next;\n }\n }\n // move forward in input list\n head = head->next;\n }\n // return sorted list\n return sorted->next;\n }\n};\n``` | 3 | 0 | ['Linked List', 'Sorting', 'C++'] | 1 |
insertion-sort-list | Java || Easiest Approach || Explained || 3 pointers || O(1) space soln | java-easiest-approach-explained-3-pointe-aam5 | ```\nclass Solution {\n \n public ListNode insertionSortList(ListNode head) {\n //making a dummy node to avoid edge cases\n ListNode dummy = | kurmiamreet44 | NORMAL | 2023-01-24T13:01:43.802911+00:00 | 2023-01-24T18:53:08.908065+00:00 | 883 | false | ```\nclass Solution {\n \n public ListNode insertionSortList(ListNode head) {\n //making a dummy node to avoid edge cases\n ListNode dummy = new ListNode(-1);\n // prev moves from starting to value who is just lesser than the next.val\n ListNode prev = dummy;\n // we use it to compare the adjacent values\n ListNode curr = head;\n ListNode next = head.next;\n dummy.next = head;\n while(next!=null)\n {\n // first check , if this is true then continue \n if(curr.val <=next.val)\n {\n curr = curr.next;\n next = curr.next;\n continue;\n }\n \n // keep moving prev as discussed \n while(prev.next !=null && prev.next.val<next.val)\n {\n prev = prev.next;\n }\n // inserting the lesser valued after prev, all the 3 pointers come in use \n curr.next= next.next;\n next.next = prev.next;\n prev.next = next;\n // initialising the pointer back to their required positions\n prev = dummy;\n next = curr.next;\n }\n \n return dummy.next;\n }\n}\n// -1 -1 5 3 4 0 \n// p c n\n// | 3 | 0 | ['Java'] | 0 |
insertion-sort-list | JAVA solutions | java-solutions-by-infox_92-4sdq | \nclass Solution {\n public ListNode insertionSortList(ListNode head) {\n ListNode dummy = new ListNode(0, head);\n \n ListNode prev = h | Infox_92 | NORMAL | 2022-11-06T08:50:46.486557+00:00 | 2022-11-06T08:50:46.486582+00:00 | 1,608 | false | ```\nclass Solution {\n public ListNode insertionSortList(ListNode head) {\n ListNode dummy = new ListNode(0, head);\n \n ListNode prev = head;\n ListNode curr = head.next;\n \n while (curr != null) {\n if (curr.val >= prev.val) {\n prev = curr;\n curr = curr.next;\n continue;\n }\n \n ListNode tmp = dummy;\n while (curr.val > tmp.next.val) {\n tmp = tmp.next;\n }\n \n prev.next = curr.next;\n curr.next = tmp.next;\n tmp.next = curr;\n curr = prev.next;\n }\n return dummy.next;\n }\n}\n``` | 3 | 0 | ['Java', 'JavaScript'] | 2 |
insertion-sort-list | C++ || Insertion Sort || An Easy and Clear Way to Sort ✔ | c-insertion-sort-an-easy-and-clear-way-t-g0ew | class Solution {\npublic:\n ListNode insertionSortList(ListNode head) {\n \n if(head == nullptr) return nullptr;\n \n int temp = | mahesh_1729 | NORMAL | 2022-10-08T13:59:33.819611+00:00 | 2022-10-08T13:59:33.819645+00:00 | 1,028 | false | class Solution {\npublic:\n ListNode* insertionSortList(ListNode* head) {\n \n if(head == nullptr) return nullptr;\n \n int temp = 0;\n for(ListNode* curr = head; curr != nullptr; curr = curr->next){\n for(ListNode* prev = head; prev != curr; prev = prev->next){\n if(curr->val < prev->val){\n temp = curr->val;\n curr->val = prev->val;\n prev->val = temp;\n }\n }\n }\n return head;\n }\n}; | 3 | 0 | ['Linked List', 'C'] | 2 |
insertion-sort-list | c++ | | 2 approches | | clear solution | c-2-approches-clear-solution-by-dhirajmi-p0g1 | 1st approch\nclass Solution {\npublic:\n\n ListNode insertionSortList(ListNode head) {\n ListNode nxt = head -> next;\n while(nxt != NULL)\n {\n | DhirajMishra_ | NORMAL | 2022-09-08T05:44:02.166293+00:00 | 2022-09-08T06:54:37.970810+00:00 | 474 | false | 1st approch\nclass Solution {\npublic:\n\n ListNode* insertionSortList(ListNode* head) {\n ListNode *nxt = head -> next;\n while(nxt != NULL)\n {\n ListNode *curr = head;\n while(curr != nxt)\n {\n if(nxt -> val < curr -> val)\n swap(curr , nxt );\n \n curr = curr -> next;\n }\n nxt = nxt -> next; \n }\n return head;\n}\n\n};\n\n2nd approch\n\nclass Solution {\npublic:\n\n ListNode* insertionSortList(ListNode* head) {\n ListNode* dummy=new ListNode(-1);\n \n ListNode* curr=head;\n \n while(curr!=NULL){\n ListNode* temp=curr->next;\n ListNode* prev=dummy;\n ListNode* nxt=dummy->next;\n \n while(nxt!=NULL){\n if(nxt->val>curr->val) break;\n \n prev=nxt;\n nxt=nxt->next;\n }\n curr->next=nxt;\n prev->next=curr;\n curr=temp;\n }\n return dummy->next;\n \n \n }\n};\n\ntime complexity for this will be - o(n). | 3 | 0 | ['Linked List', 'C'] | 1 |
insertion-sort-list | easy python solution with 69% TC | easy-python-solution-with-69-tc-by-nitan-coy5 | \ndef insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n\tdef add(node):\n\t\tcurr = self.ans\n\t\twhile(curr):\n\t\t\tif(curr.val < nod | nitanshritulon | NORMAL | 2022-09-07T05:35:09.585560+00:00 | 2022-09-07T05:35:09.585636+00:00 | 1,940 | false | ```\ndef insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n\tdef add(node):\n\t\tcurr = self.ans\n\t\twhile(curr):\n\t\t\tif(curr.val < node.val):\n\t\t\t\tprev = curr\n\t\t\t\tcurr = curr.next\n\t\t\telse: break\n\t\tnode.next, prev.next = prev.next, node\n\tself.ans = ListNode(-5001)\n\twhile(head):\n\t\ttemp, head = head, head.next\n\t\ttemp.next = None\n\t\tadd(temp)\n\treturn self.ans.next\n``` | 3 | 0 | ['Linked List', 'Python', 'Python3'] | 0 |
insertion-sort-list | Insertion Sort List | Java | Easy and Simple Solution | insertion-sort-list-java-easy-and-simple-i2oh | \n/**\n * Definition for singly-linked list.\n * public class ListNode {\n * int val;\n * ListNode next;\n * ListNode() {}\n * ListNode(int val) | Paridhicodes | NORMAL | 2022-06-27T17:12:44.657853+00:00 | 2022-06-27T17:12:44.657900+00:00 | 581 | false | ```\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 insertionSortList(ListNode head) {\n ListNode dummy=new ListNode(-10000);\n dummy.next=head;\n ListNode prev=dummy;\n ListNode curr=head;\n \n while(curr!=null){\n if(curr.val>=prev.val){\n prev=curr;\n curr=curr.next;\n }else{\n ListNode temp=dummy;\n while(temp.next.val<curr.val){\n temp=temp.next;\n }\n \n prev.next=curr.next;\n curr.next=temp.next;\n temp.next=curr;\n curr=prev.next;\n }\n }\n \n return dummy.next;\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
insertion-sort-list | Easy C++ Solution 5 lines | easy-c-solution-5-lines-by-tejesh07-quqj | I hope this solution helps you\n\nMostly in tech interviews interviewer may ask us not to use in-built functions. At that time this code might not be handy\n**\ | tejesh07 | NORMAL | 2022-06-19T12:17:55.222017+00:00 | 2022-06-19T12:17:55.222058+00:00 | 412 | false | # **I hope this solution helps you*\n\n***Mostly in tech interviews interviewer may ask us not to use in-built functions. At that time this code might not be handy***\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 */\nclass Solution {\npublic:\n ListNode* insertionSortList(ListNode* head) {\n ListNode* temp = head; //create a temp list\n while(temp->next != NULL){\n ListNode* a = temp->next; //assign next value of the temp list\n while(a){\n if(temp->val > a->val){ //compare the values\n swap(a->val, temp->val); //swap if condition fails\n }\n a = a->next;\n }\n temp = temp->next;\n } \n return head;\n }\n};\n```\n\n**Upvote if useful. Happy Coding :)** | 3 | 0 | ['Linked List', 'C'] | 0 |
insertion-sort-list | Java || Easy || Dummy | java-easy-dummy-by-amartya135-rwni | Please Upvote if you understood this (\uFF5E\uFFE3\u25BD\uFFE3)\uFF5E\n\nclass Solution {\n public ListNode insertionSortList(ListNode head) {\n ListN | amartya135 | NORMAL | 2022-04-01T14:48:16.630741+00:00 | 2022-04-01T14:48:16.630778+00:00 | 270 | false | ## **Please Upvote if you understood this** (\uFF5E\uFFE3\u25BD\uFFE3)\uFF5E\n```\nclass Solution {\n public ListNode insertionSortList(ListNode head) {\n ListNode curr = head;\n ListNode dummy = new ListNode(0);\n ListNode prev = dummy;\n ListNode nex = curr.next;\n \n while(curr!=null){\n while(prev.next != null && prev.next.val < curr.val) prev = prev.next;\n curr.next = prev.next;\n prev.next = curr;\n \n curr = nex;\n if(curr!=null) nex = curr.next;\n prev = dummy;\n \n }\n \n return dummy.next;\n }\n}\n``` | 3 | 1 | ['Java'] | 0 |
insertion-sort-list | Java Code | java-code-by-rizon__kumar-gjof | \nclass Solution {\n public ListNode insertionSortList(ListNode head) {\n ListNode start = new ListNode();\n start.next = head;\n ListNo | rizon__kumar | NORMAL | 2021-12-31T06:02:12.538580+00:00 | 2021-12-31T06:02:12.538643+00:00 | 133 | false | ```\nclass Solution {\n public ListNode insertionSortList(ListNode head) {\n ListNode start = new ListNode();\n start.next = head;\n ListNode curr = head, prev = start;\n while(curr != null){\n if(curr.next != null &&(curr.next.val < curr.val)){\n // Insertion\n while(prev.next != null && (prev.next.val < curr.next.val))\n prev = prev.next;\n ListNode temp = prev.next;\n prev.next = curr.next;\n curr.next = curr.next.next;\n prev.next.next = temp;\n prev = start;\n } else \n curr = curr.next;\n }\n return start.next;\n }\n}\n``` | 3 | 0 | [] | 0 |
insertion-sort-list | Python | Simple Solution With Explanation | python-simple-solution-with-explanation-ihsue | \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\ncl | akash3anup | NORMAL | 2021-12-15T11:40:58.912298+00:00 | 2022-03-11T07:31:37.385490+00:00 | 260 | false | ```\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 insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n currentNode = head\n previousNode = None\n while currentNode:\n if previousNode and previousNode.val > currentNode.val:\n # Detach the current node.\n detachedNode = currentNode\n previousNode.next = currentNode.next\n currentNode = currentNode.next\n # Attach the detached node at its correct position.\n\t\t\t\t# Check whether the detatched node needs to be attached at first position. If yes then update the head also.\n if head.val > detachedNode.val:\n detachedNode.next = head\n head = detachedNode\n else:\n\t\t\t\t\t# Traverse the list from start and attach the detached node at its correct position.\n tempPreviousNode = head\n tempCurrentNode = head.next\n while tempCurrentNode and tempCurrentNode.val <= detachedNode.val:\n tempPreviousNode = tempCurrentNode\n tempCurrentNode = tempCurrentNode.next\n tempPreviousNode.next = detachedNode\n detachedNode.next = tempCurrentNode \n else:\n previousNode = currentNode\n currentNode = currentNode.next\n return head\n```\n\n***If you liked the above solution then please upvote!*** | 3 | 1 | ['Linked List', 'Python'] | 0 |
insertion-sort-list | [c++] solution O(1) space | c-solution-o1-space-by-giang_it-dyb4 | The idea is to create a dummy node that would be the head of the sorted part of the list. Iterate over the given list and one by one add nodes to the sorted lis | giang_it | NORMAL | 2021-12-15T02:14:39.985026+00:00 | 2021-12-15T02:35:50.785514+00:00 | 559 | false | ##### The idea is to create a dummy node that would be the head of the sorted part of the list. Iterate over the given list and one by one add nodes to the sorted list in the appropriate place following the insertion sort algorithm.\n\n\t/**\n\t * Definition for singly-linked list.\n\t * struct ListNode {\n\t * int val;\n\t * ListNode *next;\n\t * ListNode() : val(0), next(nullptr) {}\n\t * ListNode(int x) : val(x), next(nullptr) {}\n\t * ListNode(int x, ListNode *next) : val(x), next(next) {}\n\t * };\n\t */\n\tclass Solution {\n\tpublic:\n\t\tListNode* insertionSortList(ListNode* head) {\n\t\t\tif(head == nullptr) return head;\n\n\t\t\tListNode *a = new ListNode(0);\n\t\t\tListNode *cur = head;\n\t\t\tListNode *pre = a;\n\t\t\tListNode *next = nullptr;\n\n\t\t\twhile(cur != nullptr){\n\t\t\t\tnext = cur->next;\n\t\t\t\twhile(pre->next != nullptr && pre->next->val < cur -> val){\n\t\t\t\t\tpre = pre -> next;\n\t\t\t\t}\n\n\t\t\t\tcur->next = pre->next;\n\t\t\t\tpre->next = cur;\n\t\t\t\tpre = a;\n\t\t\t\tcur = next;\n\t\t\t}\n\t\t\treturn a->next;\n\t\t}\n\t};\n\t\n**Complexity**\n* Time: O(n ^ 2) \n* Space: O(1) | 3 | 1 | ['C'] | 1 |
insertion-sort-list | C/C++ Compatible Indirect Pointer solution with O(1) space | 0ms (100%) | cc-compatible-indirect-pointer-solution-aqhh2 | <--------------\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F PLEASE UPVOTE \u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F---------- | leoslf | NORMAL | 2021-12-10T08:49:39.130249+00:00 | 2023-11-01T06:50:44.952423+00:00 | 247 | false | <--------------\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F PLEASE UPVOTE \u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F\u2B06\uFE0F--------------->\n\nUsing an indirect pointer to the run (where we tried to maintain the sorted partition up to) and perform sorted insert between `head` and `*run`.\n\nDetailed Explanation at each step:\n```\n// Case 1: we still have a sorted list up to `*run`: if (*run)->val >= max\n| <= x | x | ... |\n|<- sorted ->|<- unsorted ->|\n ^max == *run\n// so, we can just advance the run to it\'s pointee\'s `next`\n------------------------------------------------------------\n// Case 2: we have to move`*run` in front to maintain the non-descreasing sequence: if (*run)->val < max\n| < x | >= x | x | ... |\n|<- sorted ->|<- unsorted ->|\n ^head ... ^max ^(*run)\n\n// Now, just perform a sorted insert of `*run`, between `head` and `max`\n// we can declare an indirect pointer `indirect` initialized to address of `head`, and\n// iterate until it points to a node such that node->val >= x (i.e. (*run)->val)\n| < x | >= x | x | ... |\n|<- sorted ->|<- unsorted ->|\n ^(*indirect) (the first node of the >= x partition)\n\n// finally we can remove the pointee of `run` (i.e. `*run`) and insert at `*indirect`, such that\n| < x | x | >= x | ... |\n|<- sorted ->|<- unsorted ->|\n ^max ^(*run)\n// NOTE: run is the address of the `next` of the node having `val` == max\n// NOTE: we don\'t need to advance the run pointer in this case\n```\n\n\nCode:\n```C++\nclass Solution {\npublic:\n void insert_before(ListNode **at, ListNode *node) {\n node->next = *at;\n *at = node;\n }\n \n ListNode *remove(ListNode **at) {\n ListNode *result = *at;\n *at = result->next;\n result->next = NULL;\n return result;\n }\n \n ListNode *insertionSortList(ListNode *head) {\n ListNode **run = &head;\n \n int max = INT_MIN;\n \n // until the last node\n while (*run) {\n max = std::max(max, (*run)->val);\n \xA0 \xA0 \xA0 \xA0 \xA0 \xA0if ((*run)->val < max) {\n \xA0 \xA0 \xA0 \xA0 \xA0 \xA0 \xA0 // case 2: sorted insert\n \xA0 \xA0 \xA0 \xA0 \xA0 \xA0 \xA0 \xA0ListNode **indirect = &head;\n \xA0 \xA0 \xA0 \xA0 \xA0 \xA0 \xA0 // walk to the next node until we hit the first node of the larger partition\n while ((*indirect)->val < (*run)->val)\n indirect = &(*indirect)->next;\n \n insert_before(indirect, remove(run));\n } else {\n // case 1\n run = &(*run)->next;\n }\n }\n return head;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
insertion-sort-list | Java Easy Solution | java-easy-solution-by-thinagaran-0802 | \nclass Solution {\n public ListNode insertionSortList(ListNode head) {\n \n ListNode temp = head;\n int n=0;\n while(temp!=null) | Thinagaran | NORMAL | 2021-11-12T13:36:04.503353+00:00 | 2021-11-12T13:36:04.503384+00:00 | 407 | false | \nclass Solution {\n public ListNode insertionSortList(ListNode head) {\n \n ListNode temp = head;\n int n=0;\n while(temp!=null)\n {\n n++;\n temp=temp.next;\n }\n temp=head;\n \n int arr[] = new int[n];\n int i=0;\n while(temp!=null)\n {\n arr[i]=temp.val;\n i++;\n temp=temp.next;\n }\n \n for(i=1;i<n;i++)\n {\n for(int j=i;j>0;j--)\n {\n if(arr[j-1]>arr[j])\n {\n int a=arr[j];\n arr[j]=arr[j-1];\n arr[j-1]=a;\n }\n else\n {\n break;\n }\n }\n }\n \n temp=head;\n i=0;\n while(temp!=null)\n {\n temp.val =arr[i];\n i++;\n temp=temp.next;\n }\n \n return head;\n }\n} | 3 | 5 | ['Array', 'Java'] | 1 |
insertion-sort-list | C++ Solution || 16ms O(1) space | c-solution-16ms-o1-space-by-thanos_ashu-chc2 | \n/**\n * Definition for singly-linked list.\n * struct ListNode {\n * int val;\n * ListNode *next;\n * ListNode() : val(0), next(nullptr) {}\n * | thanos_ashu | NORMAL | 2021-10-28T13:28:25.493064+00:00 | 2021-10-28T13:28:25.493103+00:00 | 137 | false | ```\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* insertionSortList(ListNode* head) {\n ListNode *dummy = new ListNode(-500000), *node;\n dummy->next = head;\n node = dummy;\n while(head)\n {\n if(node->val > head->val)\n {\n node->next = head->next;\n ListNode *ptr = dummy;\n while(ptr->next->val <= head->val)\n ptr = ptr->next;\n head->next = ptr->next;\n ptr->next = head;\n head = node->next;\n }\n else\n {\n node = node->next;\n head = head->next;\n }\n }\n \n return dummy->next;\n \n }\n};\n``` | 3 | 0 | [] | 0 |
insertion-sort-list | FASTER than 96.02%, C++, Clean Code | faster-than-9602-c-clean-code-by-aditiba-hyxq | Insertion Sort for Linked list.\n->Create a dummy node at the start of the linked list\n->Traverse the list start till end and for each node insert it at the ri | aditibahl | NORMAL | 2021-07-04T12:02:02.577352+00:00 | 2021-07-04T12:25:12.950103+00:00 | 379 | false | Insertion Sort for Linked list.\n->Create a dummy node at the start of the linked list\n->Traverse the list start till end and for each node insert it at the right position by using temporary node prev that tells us the right position for the node.\n->Return the next node of dummy as that will be the starting of linked list.\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 */\nclass Solution {\npublic:\n ListNode insertionSortList(ListNode head) {\n ListNode dummy=new ListNode();\n dummy->next=head;\n ListNode curr=head,prev=dummy;\n while(curr){\n if(curr->next && curr->next->val<curr->val){\n ListNode nxt=curr->next->next;\n ListNode insert=curr->next; //node to be inserted at right position\n while(prev->next->val<insert->val)\n prev=prev->next; //takes us to the last node whose value is more than the node to be inserted\n curr->next=nxt;\n insert->next=prev->next;\n prev->next=insert;\n prev=dummy; //again initialized to dummy for next comparisions\n }\n else\n curr=curr->next;\n }\n return dummy->next;\n }\n};\n``` | 3 | 0 | ['C'] | 0 |
insertion-sort-list | PYTHON SOL WITH LINE BY LINE EXPLANATION | python-sol-with-line-by-line-explanation-96dp | I have already added the required comments and explanation and if you still have any doubts comment down\n\n \n \n """\n We will cre | shubhamverma2604 | NORMAL | 2021-03-29T07:30:35.570179+00:00 | 2021-03-29T07:31:04.889931+00:00 | 342 | false | I have already added the required comments and explanation and if you still have any doubts comment down\n\n \n \n """\n We will create a sorted linked list based on the given linkedlist by taking one val at a time and\n iterating and checking with prev and next pointer \n \n """\n \n \n #The basic idea is we will create a dummy variable\n #the reason we are creating a dummy variable so that we an have a pointer\n #to our prev_pointer and curr_pointer \n #and the reason we are taking prev pointer and next pointer so that we can compare it with \n #the curr.val and place it accordingly\n \n \n """\n Initially the prev pointer will be pointing to our dummy var and the next pointer will be pointing to the prev.next \n \n And each iteration we will be moving both our pointers\n \n \n """\n dummy_head = ListNode()\n \n curr = head\n \n while curr:\n prev_pointer = dummy_head\n next_pointer = prev_pointer.next\n \n \n #Now we will try to find out what would be the correct position be for the curr\n #value we are at\n \n while next_pointer: #Dont include prev_pointer coz initially it will be null\n \n if curr.val < next_pointer.val:\n break \n \n \n prev_pointer = prev_pointer.next\n next_pointer = next_pointer.next\n \n #Now that we find out the correct poistion all we need to do is update our pointers\n \n #point to be noted if we simply do curr = curr.next then we will loose the track of original/previous curr.next \n \n #As we are initializing the curr.next = next_pointer\n \n #So to avoid that we are storing it in a temp variable \n \n temp = curr.next\n \n curr.next = next_pointer\n prev_pointer.next = curr\n \n curr = temp\n \n return dummy_head.next # Coz the dummy_head has no value that is 0 so we will start from the next node\n\t\t\n\t\t\n**UPVOTE IF YOU FIND IT HELPFUL**\n | 3 | 0 | ['Linked List', 'Two Pointers', 'Python', 'Python3'] | 0 |
insertion-sort-list | Java Solution With Detailed Explaination | java-solution-with-detailed-explaination-nhmv | Explaination\n\n\t\thead : 1 -> 2 -> 4 -> 3 ->null\n\t\t\n\t\tdummyHead : (0)-> 1 -> 2 -> 4 ->3 -> null\n\t\t\n\t\t1 -> 2 -> 4 -> 3 -> null\n\t\t\t | |\n\t\t | credit_card | NORMAL | 2020-10-13T11:46:40.198468+00:00 | 2020-10-13T11:48:41.863044+00:00 | 146 | false | **Explaination**\n```\n\t\thead : 1 -> 2 -> 4 -> 3 ->null\n\t\t\n\t\tdummyHead : (0)-> 1 -> 2 -> 4 ->3 -> null\n\t\t\n\t\t1 -> 2 -> 4 -> 3 -> null\n\t\t\t | |\n\t\t head (head.val <= head.next.val) => continue\n\t\t \n\t\t\t\t\t head\n\t\t\t\t\t \t |\n\t\t(0) -> 1 -> 2 -> 4 -> 3 -> null\n\t\t\t\t | |\n\t\t\t preNode insertNode\n\t\tFind preNode by checking it value with insertNode\n\t\tConnect next of head to next of insertNode \n\t\t\n\t\t(0) -> 1 -> 2 -> 4 -> null (connect head to next of insertion node to break the node from the list and to add it in correct position)\n\t\t\n\t\t\n\t\t(0) -> 1 -> 2 -> 4 -> null (connect next of insertion node to to pre node )\n\t\t\t\t\t|\n\t\t\t\t\t3\n\t\t\t\t\t\n\t\t(0) -> 1 -> 2 -> 3 -> 4 -> null (finally connect the next of pre node to add the insertion node into list)\n```\n\n**Code**\n```\npublic ListNode insertionSortList(ListNode head) {\n //base case \n ListNode dummyHead = new ListNode(0);\n dummyHead.next = head; \n ListNode preNode = dummyHead;\n ListNode insertNode = dummyHead;\n while(head != null && head.next != null){\n if(head.val <= head.next.val){\n //in ascending order , no need to change\n head = head.next;\n }\n else{\n //move the prenode to the start of the dummyhead\n preNode = dummyHead;\n //the node to insert in its correct position is the node next to the actual head\n insertNode = head.next;\n //find the pos to insert the current node (insertNode) by checking if pre node values are less than the value of the node to be inserted\n while(preNode.next.val < insertNode.val){\n preNode = preNode.next;\n }\n //now next of the pre node is the place where the cuurent node (insertNode) to be inserted\n //connect the original head to next of insertion node to break the node from the list and to add it in correct position\n head.next = insertNode.next;\n //connect next of insertion node to to pre node \n insertNode.next = preNode.next;\n //finally connect the next of pre node to add the insertion node into list\n preNode.next = insertNode;\n }\n }\n return dummyHead.next;\n }\n``` | 3 | 0 | ['Java'] | 0 |
insertion-sort-list | [JavaScript] Clear and Easy to understand with ES6 | javascript-clear-and-easy-to-understand-rf2lw | \nvar insertionSortList = function(head) {\n let newHead = new ListNode(0)\n while(head){\n const t = head\n head = head.next\n let c | kaiyiwing | NORMAL | 2020-07-25T02:10:17.324588+00:00 | 2020-07-25T02:12:08.557621+00:00 | 635 | false | ```\nvar insertionSortList = function(head) {\n let newHead = new ListNode(0)\n while(head){\n const t = head\n head = head.next\n let cur = newHead\n while(cur){\n if(!cur.next || t.val <= cur.next.val){\n [cur.next, t.next] = [t, cur.next]\n break\n }\n cur = cur.next\n }\n }\n return newHead.next\n};\n``` | 3 | 0 | ['JavaScript'] | 1 |
insertion-sort-list | C++ Easy Solution in O(1) space. | c-easy-solution-in-o1-space-by-manakupad-sghv | \nListNode* insertionSortList(ListNode* head) {\n // if list is empty or has only one node\n if(head == NULL || head->next == NULL)\n r | manakupadhyay | NORMAL | 2020-06-15T20:07:01.860776+00:00 | 2020-06-15T20:07:01.860823+00:00 | 212 | false | ```\nListNode* insertionSortList(ListNode* head) {\n // if list is empty or has only one node\n if(head == NULL || head->next == NULL)\n return head;\n\t\t\t\n // make an empty list, it will store nodes in sorted order\n ListNode* newList = NULL;\n \n ListNode* current = head;\n \n while(current!=NULL){\n \n // store current\'s next in a variable\n ListNode* nextt = current->next;\n \n // insert this node is its correct position in the new list.\n if(newList == NULL || newList->val >= current->val){\n ListNode* temp = newList;\n newList = current;\n newList->next = temp;\n }\n else\n {\n ListNode* temp = newList;\n while(temp && temp->next && temp->next->val <= current->val)\n {\n temp = temp->next;\n }\n ListNode* t = temp->next;\n temp->next = current;\n temp->next->next=t;\n }\n // go the the next node\n current = nextt;\n }\n return newList;\n }\n``` | 3 | 0 | [] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.