Dare2Solve
This problem involves [describe the problem context, e.g., working with a specific data structure or solving a particular type of problem]. The goal is to [explain the main objective of the problem]. The problem tests the understanding of [mention any specific concepts, e.g., algorithms, data structures] and how they can be applied to achieve the desired solution.
The intuition behind solving this problem lies in [explain the key idea or insight needed to solve the problem]. By understanding [mention any underlying principle or observation], we can approach the problem more effectively. The key is to [describe what the solver needs to focus on or the main strategy they should employ].
The time complexity of this solution is (O([explain time complexity])), where (n) is [describe what (n) represents, e.g., the number of elements, size of input, etc.]. This is because [give a brief explanation of why this is the time complexity].
The space complexity is (O([explain space complexity])), as [explain why this amount of space is needed, considering any auxiliary space used].
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
if (!head)
return nullptr;
std::vector<int> arr;
ListNode* current = head;
while (current) {
arr.push_back(current->val);
current = current->next;
}
for (int i = 1; i < arr.size(); i++) {
int currVal = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > currVal) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = currVal;
}
current = head;
for (int i = 0; i < arr.size(); i++) {
current->val = arr[i];
current = current->next;
}
return head;
}
};
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
if not head:
return None
arr = []
current = head
while current:
arr.append(current.val)
current = current.next
for i in range(1, len(arr)):
curr_val = arr[i]
j = i - 1
while j >= 0 and arr[j] > curr_val:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = curr_val
current = head
for i in range(len(arr)):
current.val = arr[i]
current = current.next
return head
class Solution {
public ListNode insertionSortList(ListNode head) {
if (head == null) return null;
List<Integer> arr = new ArrayList<>();
ListNode current = head;
while (current != null) {
arr.add(current.val);
current = current.next;
}
for (int i = 1; i < arr.size(); i++) {
int currVal = arr.get(i);
int j = i - 1;
while (j >= 0 && arr.get(j) > currVal) {
arr.set(j + 1, arr.get(j));
j--;
}
arr.set(j + 1, currVal);
}
current = head;
for (int i = 0; i < arr.size(); i++) {
current.val = arr.get(i);
current = current.next;
}
return head;
}
}
var insertionSortList = function (head) {
let current = head;
const arr = [];
while (current) {
arr.push(current.val);
current = current.next;
}
for (let i = 1; i < arr.length; i++) {
let currVal = arr[i];
let j = i - 1
for (; j >= 0 && arr[j] > currVal; j--) {
arr[j + 1] = arr[j];
}
arr[j + 1] = currVal;
}
current = head;
for (let i = 0; i < arr.length; i++) {
current.val = arr[i];
current = current.next;
}
return head
};