Sailing Into the Storm - #Day 9
Merge K Sorted Lists (Leetcode Problem) - I4G 10 Days Of Code Challenge
Table of contents
Yesterday, I asked myself a question, seeing how easy yesterday's challenge was, and how the challenges (except yesterday) had been getting harder, Was this the notorious calm before the storm? ๐คจ. I decided to leave the answer to of my question to time, and it seems time has come up with an answer.
According to the Leetcode rankings of the problems we have had so far, this was supposed to be, the hardest problem we've faced yet.
Let's get into what should be our hardest challenge yet shall we?
The Challenge
Our first hard problem!!! ๐จ ๐
The linked lists are objects which have a custom definition and properties val
and next
/**
* Definition for a singly-linked list.
* class ListNode {
* public $val = 0;
* public $next = null;
* function __construct($val = 0, $next = null) {
* $this->val = $val;
* $this->next = $next;
* }
* }
*/
Approach to Solution
The first thing I did was to explore the nature of the linked list objects (listNode
) and get familiar with them and figure out their structure.
// What the linked list looks like on the results tab
$list = [2,3,4]
// What the linked list really is
$list = new listNode(2, new listNode(3, new listNode(4)))
After understanding this structure, it was clear that working with this would require extensive use of loops. With this and the challenge prompt, I came up with an algorithm like this:
- Take all the values individually from the linked lists input
list
and add them to an array - Sort the array
- Convert the array back to a linked list using the
listNode
class.
With a clear process in mind to my solution, I jumped into the code. Using a foreach
loop and the array_push()
function, I extracted all the values in the linked list and added them to an array.
From there, I used the sort()
function on my converted array to arrange them in an ascending order.
With that done, using another foreach
loop, I put the values of the array into a linked list and returned the list.
Tests and Trials
The first version of the code which I wrote easily passed through the example test cases but failed when submitted because, there were some test cases which did not work like when the input list
is [[],[]]
.
Honestly speaking, I do not know why anyone would input such as a value but, I went back to my code and tried two approaches:
- Create a condition when the first list is empty
- Ignore empty linked lists.
The first approach clearly failed as there were also scenarios where the second linked list was not empty, e.g. [[],[1]]
The second approach however worked, it took more time and tinkering but I discovered my first code, basically reassigned to the next
property before adding the value to the array which could possibly add null
values into the converted array.
I fixed it by rearranging my code to first add a value to the array if the list/number in question is not null.