Coding Challenge 4

The Problem

Another coding challenge for us today, let’s see what we have.

This problem was asked by Google.

Given a singly linked list and an integer k, remove the kth last element from
the list. k is guaranteed to be smaller than the length of the list.

The list is very long, so making more than one pass is prohibitively expensive.

Do this in constant space and in one pass.

Daily Coding Problem

I will be tackling this problem in PHP.

The Theory

I am going to tackle this the simplest way I can think of, and that is using the unset() function in PHP.

We will create a function that takes the list and k as arguments and returns the list with the correct element removed (hopefully).

The Code

We create a function removeNthFromArray() that takes the two arguments $array and $k. The problem asks for us to remove the kth element from the end of the array, so to calculate that position we pass the length of the array minus $k into the unset() function. Passing an array element into the unset() function removes that element from the array. We simply return the amended array after that.

function removeNthFromArray(array $array, int $k){
    unset($array[count($array)-$k]);
    return $array;
}

Next, we write some simple test cases and check the results

// Test Cases
$testlist1 = ['Dave', 'Martin', 'John', 'Tim', 'Gary'];
$testlist2 = [1,5,7,66,12234,86];

// Tests
print_r(removeNthFromArray($testlist1,2)); // Prints Dave, Martin, John, Gary
print_r(removeNthFromArray($testlist2,5)); // Prints 1,7,66,12234,86

Conclusion

And there we have it, a fairly simple problem to solve in PHP using the inbuilt functions available to us.

Leave a Reply