You can't do arr.remove(j)
because there can be duplicate numbers, say an example case as [1,2,3,4,5,20,6,7,8,20]
.
I solved this in javascript
but since you mention algorithm
tag, answers can be language-agnostic
.
Approach:
We can create a circular doubly linked list of the given numbers. So, for [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
, the list would look like:
_____
| |
both next and prev links(double arrow notation) v |
-1 <--> 2 <--> 3 <--> 4 <--> 5 <--> 6 <--> 7 <--> 8 <--> 9 <--> 10 -- | prev link
| ^ | |
| |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _next link_ _ | |
|_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _|
For each step, we add the current value of the node in iteration to result. Before moving on to the next to next node(because we skip in the middle), we would do below 2 steps:
temp.prev.next = temp.next;
temp.next.prev = temp.prev;
which means that we assign previous node's next
value to next node of current node and next node's previous value to current node's previous value.
After first step of iteration, our new(as in modified) circular DLL would look like below:
______
| |
both next and prev link v |
-2 <--> 4 <--> 6 <--> 8 <--> 10 -- |
| ^ | |prev link
| |_ _ _ _ _ _ _ _ _next link_ _ _ | |
|_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _|
Likewise, you can generate how the list would look like for each step.
Snippet:
function yesNo(arr) {
var result = [];
var head = null,
temp = null;
for (var i = 0; i < arr.length; ++i) {
if (head == null) {
head = createNode(arr[i]);
temp = head;
} else {
var temp2 = createNode(arr[i]);
temp.next = temp2;
temp2.prev = temp;
temp = temp2;
}
}
temp.next = head;
head.prev = temp;
temp = head;
while (temp.next != temp) {
result.push(temp.value);
temp.prev.next = temp.next;
temp.next.prev = temp.prev;
temp = temp.next.next; // skip next and go to next to next
}
result.push(temp.value);
return result;
}
function createNode(val) {
return {
value: val,
prev: null,
next: null
};
}
console.log(yesNo([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])); console.log(yesNo(['this', 'code', 'is', 'right', 'the']));
Time Complexity: O(n)
Space Complexity: O(n)
where n
is number of elements in the array.