Skip to content
Advertisement

Moving character efficiently on a row

Given input (items = 6, position = 3)

creates a row of 6 items and a character positioned on item 3 {0,1,2,[3],4,5}

A call to left() moves the character two positions to the left and the item at position 3 is removed {0,[1],2,4,5}

The next call to right() moves the character two positions to the right and the item at position 1 is removed {0,2,[4],5}

Then calling position() method now should return 4.

The character will not move to the left or right if no items are present so no need to implement that.

JavaScript

This code works perfectly for small inputs, but I am getting performance errors when the input is large.

How to implement this efficiently? I don’t have test case details for the error related to performance errors.

Advertisement

Answer

As it already has been pointed outed both in the comments and the answer by @AbhinavMathur, in order to improve performance you need to implement Doubly linked list data structure.

Note that it’s mandatory to create your own implementation that will maintain a reference to the current node. Attempt to utilize an implementation built-in in the JDK in place of the items array will not buy you anything because the advantage of the fast deletion will be nullified by the cost of iteration (in order to reach the element at position n, LinkedList needs to crawl through the n elements starting from the head, and this operation has a liner time complexity).

Methods left(), right() and position() will have the following outcome:

  • left() – in case when the previous node (denoted as prev in the code) associated with current is not null, and in tern its previous node exists, the current node will be dereferenced (i.e. next and previous nodes associated with the current node will be linked with each other), and the variable current would be assigned to the prev of the previous node, i.e. current.prev.prev. Time complexity O(1).

  • right() – in case when the next node (denoted as next in the code) associated with current is not null, and in tern its next node exists, the current node will be dereferenced in a way that has been described above, and the variable current would be assigned to the next of the next node, i.e. current.next.next. Time complexity O(1).

  • position() – will return a value of the current node. Time complexity O(1).

That’s how it might look like:

JavaScript

A link to Online Demo

Advertisement