Given a linked list that stores a path formed by cells of a matrix, remove the redundant nodes in that path. The path can be both vertical and horizontal, but never diagonal. To determine the complete path, we need the endpoints of all vertical and horizontal paths; middle nodes don’t provide any value and are therefore redundant. So, the resultant list should contain coordinates of only endpoints of all vertical and horizontal paths.

For example,

Redundant nodes in Linked List

We should convert the above list into the following list:

Redundant nodes removed from linked list

Practice this problem

We can easily solve the problem by traversing the list and considering three nodes at a time. If a triplet is found with the same x–value or same y–value, then delete the middle node. If this is done for all adjacent triplets, we will get the desired list at the end.

This is demonstrated below in C, Java, and Python:

C


Download  Run Code

Output:

(0, 1) —> (0, 8) —> (7, 8) —> (7, 12) —> NULL

Java


Download  Run Code

Output:

(0, 1) —> (0, 8) —> (7, 8) —> (7, 12) —> null

Python


Download  Run Code

Output:

(0, 1) —> (0, 8) —> (7, 8) —> (7, 12) —> None

The time complexity of the above solution is O(n), where n is the total number of nodes in the linked list, and doesn’t require any extra space.