Move array to the right, and make missing space 0 - javascript

I am trying to move an array to the right by a set value, and replacing the now missing spaces with 0. I just can not figure out how to do it.
Array before moving:
let array = [1,2,3,4,5,6,7]
Array after moving 2 to the right:
array = [0,0,1,2,3,4,5]
Ive looked at other stack overflow posts but those just wrap around the data making a move to the right look like this:
array = [6,7,1,2,3,4,5]
Whilst I want to just remove the 6 and 7.

Just unshift with 0's and the pop off the last numbers.
function shiftArray(arr, numberOf0s) {
for (let i = 0; i < numberOf0s; i++) {
arr.unshift(0);
arr.pop();
}
}
function shiftArray(arr, numberOf0s) {
for (let i = 0; i < numberOf0s; i++) {
arr.unshift(0);
arr.pop();
}
return arr;
}
let array = [1,2,3,4,5,6,7];
console.log(array);
shiftArray(array, 2);
console.log(array);

As with most languages manipulating an array type data structure anywhere other than the back via methods like insert, unshift is not ideal. This is because of the way elements of an array are stored in memory i.e., contiguously. For this reason, each insert or unshift operation requires moving all the elements after it every time to maintain this "contiguousness". Basically, you should avoid using these methods unless you absolutely have to when working with arrays.
Luckily in this case you can just iterate over the array in reverse and copy the element to its correct position and fill in the remaining slots with zeros for an O(n) solution where n is the length of the array:
const moveToRight = (array, n) => {
if (array === undefined || array.length == 0) {
return;
}
if (n < 0) {
throw 'Error n cannot be negative!';
}
let i = array.length - 1;
while (i >= 0 + n) {
array[i] = array[i - n];
i--;
}
while (i >= 0) {
array[i] = 0;
i--;
}
return;
}
array = [1, 2, 3, 4, 5, 6, 7];
try {
moveToRight(array, 2);
} catch (e) {
console.error(e);
}
console.log(array);

Related

Write a function getDuplicates

Write a function getDuplicates that returns an array of all the elements that appear more than once in the initial items array (keeping the order). If an element appears many times, it should still be added to the result once.
This is my code
function getDuplicates(items) {
let result = [];
if (items === [0,0,0,0]) {return [0]}
for (let i = 0; i < items.length; i++) {
for (let j = i + 1; j < items.length; j++) {
if (items[i] === items[j]) {
result.push(items[i])
}
}
}
return result
}
I get an error:
input: [0, 0, 0, 0]
Hide details
Expected:
[0]
Received:
[0,0,0,0,0,0]
In JavaScript, arrays are objects, so when you use the === operator to compare two arrays, it will only return true if they are the exact same object in memory.
Use a Set to track duplicates: Instead of using an array to store the duplicate elements, we can use a Set to make sure we don't add duplicates to the result array. A Set is an efficient data structure for checking if an element exists or not, and it also automatically removes duplicates.
Use a single loop: Instead of using two nested loops to compare every element with every other element, we can use a single loop to keep track of the elements we've seen so far, and add them to the result if we see them again.
function getDuplicates(items) {
const result = [];
const seen = new Set();
for (const item of items) {
if (seen.has(item) && !result.includes(item)) {
result.push(item);
} else {
seen.add(item);
}
}
return result;
}
console.log(getDuplicates([0, 1, 0, 1, 2]))
a modified version of yours
function getDuplicates(items) {
let result = [];
let added = {};
for (let i = 0; i < items.length; i++) {
if (!added[items[i]] && items.indexOf(items[i], i + 1) !== -1) {
result.push(items[i]);
added[items[i]] = true;
}
}
return result;
}
console.log(getDuplicates([0, 1, 0, 1, 2]))
or in short doing the same
const getDuplicates = items => items.filter((item, index) => items.indexOf(item) !== index && items.lastIndexOf(item) === index);
console.log(getDuplicates([0, 1, 0, 1, 2]))
The best way to filter out the unique elements in an array is JavaScript Set
You cannot compare two arrays just like array1 === array2 because, Arrays have the type Object and you cannot compare two object just with equal to operator. Objects are not compared based on their values but based on the references of the variables. So when you compare two arrays which have same values using array1 === array2, it will compare its memory location only, not its values. So it will be only false.
The best way to achieve your result is to create an Array by checking the number of occurrences of nodes in the parent array, having occurrences count more than one and use a Set to remove the repetitions
function getDuplicates(items) {
return Array.from(new Set(items.filter(node => items.filter(x => node === x).length > 1)))
}
console.log(getDuplicates([0, 1, 0, 1, 2]))
You can try it:
Check if the current number is duplicated by using filter to check the length of an array.
Check if the result array contains duplicates.
function getDuplicates(items) {
let result = [];
for (let i = 0; i < items.length; i++) {
if ((items.filter(item => item == items[i])).length > 1 && !result.includes(items[i])) {
result.push(items[i]);
}
}
return result;
}
console.log(getDuplicates([0, 0, 0, 0]));
So. first of all - comparing 2 array will not work, (Somebody already explained why above).
Your code doesn't work because of if statement. You're checking if an array doesn't have any value except 0.
Try summing all numbers in the array and check if it's 0.
if(arr.reduce((accum, curr) => return accum += curr) == 0) {
return [0];
}
Your code is close, but there are a few issues that need to be addressed. First, you should not use the strict equality operator === to compare arrays, because it checks whether the two arrays have the same reference, not the same elements. Instead, you can use the JSON.stringify() method to compare the string representations of the arrays.
Second, your code only returns [0] if the input array is [0,0,0,0], which is not a general solution for finding duplicates. You can use an object to keep track of the count of each element in the array, and then add the elements that have a count greater than 1 to the result array.
Here's the corrected code:
function getDuplicates(items) {
let result = [];
let count = {};
for (let i = 0; i < items.length; i++) {
if (count[items[i]] === undefined) {
count[items[i]] = 1;
} else {
count[items[i]]++;
}
}
for (let i = 0; i < items.length; i++) {
if (count[items[i]] > 1 && result.indexOf(items[i]) === -1) {
result.push(items[i]);
}
}
return result;
}
This code keeps track of the count of each element in the count object, and then adds the elements that have a count greater than 1 to the result array, while making sure not to add duplicates to the result.

Find First and Last Position of Element in Sorted Array

I am trying to solve the LeetCode problem Find First and Last Position of Element in Sorted Array:
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
You must write an algorithm with O(log n) runtime complexity.
I am writing this code:
var searchRange = function(nums, target) {
nums = nums.sort((a, b) => (a-b))
let result = [];
for(let i = 0; i < nums.length; i++) {
if (nums[i] == target) {
result.push(i)
} else {
result = [-1, -1]
}
}
return result
};
console.log(searchRange([5,7,7,8,8,10], 8));
It should return:
[3, 4]
but it returns:
[-1, -1]
What is wrong?
Your else code is wiping out results from the previous iteration of the loop.
However, your code is not efficient:
First, it calls sort on an array that is given to be already sorted: so leave that out.
Secondly, as your code is visiting every element in the array, you still get a time complexity of O(n), not O(logn).
To get O(logn) you should implement a binary search, and then perform a search to find the start of the range, and another to find the end of it.
Here is how that could work:
function binarySearch(nums, target) {
let low = 0;
let high = nums.length;
while (low < high) {
let mid = (low + high) >> 1; // half way
if (nums[mid] > target) {
high = mid;
} else {
low = mid + 1;
}
}
return high; // first index AFTER target
}
function searchRange(nums, target) {
let end = binarySearch(nums, target);
let start = binarySearch(nums, target - 1);
return start === end ? [-1, -1] : [start, end - 1];
}
console.log(searchRange([5,7,7,8,8,10], 8));
You loop does not have a good exit condition. Loop iterates till the last element and if the last element does not match, it sets -1,-1 into the result.
Intermediate values of result are ignored.
Other problems:
You're given a sorted array, so don't sort it again. That's heavy.
When you iterate over all elements, it has O(n) time complexity.
Solution:
Binary search to find any one occurence of the element - save the index where the value is found.
Use the index found to check left and right adjacent elements in the original array to find the start and end positions.
function searchRange(r,n){
var s = r.sort((a,b)=>a-b);
return [s.indexOf(n), s.lastIndexOf(n)];
}
console.log('result 1',searchRange([5,7,7,8,8,10], 8))
console.log('result 2',searchRange([5,7,7,6,6,10], 8))
You were on the right track, its just your logic. You are setting result to [-1, -1] if ANY index of nums after the last target index is not equal to the target. So you want to have the check outside of the for loop.
var searchRange = function(nums, target) {
nums = nums.sort((a, b) => (a-b));
let result = [];
for(let i = 0; i < nums.length; i++) {
if (nums[i] == target) {
result.push(i);
}
}
return (result.length == 0) ? [-1, -1] : result;
};
console.log(searchRange([5,7,7,8,8,10], 8));
Note: This will not be the final solution because this will return EVERY index that contains target
Dart
if (nums.isEmpty || !nums.contains(target)) {
return [-1, -1];
} else {
return [nums.indexOf(target), nums.lastIndexOf(target)];
}

Recursively going through permutations without storing in memory

I'm trying to go through all possible permutations of an array using a recursive function.
The permutations don't need to be stored in memory. They are being processed right away by the recursive function.
The idea is that the recursive function has an argument 'used' which keeps track of the elements that are 'fixed' at this point in the recursion tree, and an argument 'free' which keeps track of the elements that are not fixed yet at this point (i.e. they will be rearranged in the recursion steps going down the tree from there). So the first time, the function is called with an empty 'used' array and a full 'free' array.
Somehow my code below doesn't work yet. It only processes the first permutation successfully.
const elements = [7, 23, 41, 65, 99]
const n = elements.length;
handlePermutations([], elements);
function handlePermutations(used, free) {
if (used.length<n) {
for (i = 0; i < free.length; i++) {
newUsed = used.concat(free[i]); // add element i from free to used
newFree = free.filter(x => x != free[i]) // remove element i from free
handlePermutations(newUsed, newFree);
}
} else {
// ... 'process' this permutation (do something useful with it) ...
}
}
You're using (implicitly declared) global i, so it doesn't reset for each functions.
change it to let i fix the problem
const elements = [7, 23, 41, 65, 99]
const n = elements.length;
handlePermutations([], elements);
function handlePermutations(used, free) {
if (used.length < n) {
for (let i = 0; i < free.length; i++) {
let newUsed = used.concat(free[i]); // add element i from free to used
let newFree = free.filter(x => x != free[i]) // remove element i from free
handlePermutations(newUsed, newFree);
}
} else {
console.log(...used)
// ... 'process' this permutation (do something useful with it) ...
}
}
btw, your current free.filter(...) breaks if you have duplicate items. One possible way is simply change it to check passed in index.
free.filter((x,index) => index!=i)
Out of interest, here is a generator version of the same algorithm (with some changes).
const elements = [1, 2, 3, 4, 5]
for (let item of Permutations(elements)) {
console.log(...item)
}
// note: this (OP's) algorithm use O(n**2) space afaict
function Permutations(elements) {
return handlePermutations([], elements)
function* handlePermutations(used, free) {
if (free.length == 0)
yield used;
else {
for (let i = 0; i < free.length; i++) {
let newUsed = used.concat(free[i]) // add element i from free to used
let newFree = free.filter((x, index) => index != i) // remove element i from free
yield* handlePermutations(newUsed, newFree);
}
}
}
}
Another approach has you pass the callback function that will be used with each permutation.
const excludeIndex = (i) => (xs) =>
[... xs .slice (0, i), ... xs .slice (i + 1)]
const handlePermutations = (fn) => (free, used = []) =>
free.length == 0
? fn (used)
: free .forEach (
(e, i) => handlePermutations (fn) (excludeIndex (i) (free), [...used, e])
)
handlePermutations (xs => console. log(...xs)) ([7, 23, 41, 65])
.as-console-wrapper {max-height: 100% !important; top: 0}
We include the simple helper excludeIndex, which returns a copy of the array with the index missing. We use that in the recursive call along with the concatenation of the current element to used.
I'm not much of a fan of code written only for side-effects, but as that is the fundamental goal in the question, I can certainly live with it here.
Time complexity is unavoidably O (n!). Space complexity I think is O (n), since free and used together hold the original n elements. (Oops, see the comments!) Space complexity is O (n^2)
A different approach to this. Using a single integer to determine a distinct permutation of that array.
So generating all permutations for an array and processing them would be:
function permutation(array, n) {
let result = array.slice(); // don't mutate the input
for (let i = 0, rest = result.length; rest > 1 && n > 0; ++i, n = Math.floor(n / rest--)) {
let j = n % rest + i;
if (i === j) continue;
const tmp = result[i];
result[i] = result[j];
result[j] = tmp;
}
return result;
}
const elements = [1, 2, 3, 4, 5];
const length = elements.reduce((a,_,i) => a*(i+1), 1);
//const length = 5 * 4 * 3 * 2 * 1;
const map = {};
for (let i = 0; i <= length; ++i) {
map[i] = permutation(elements, i).join();
}
console.log(map);
console.log("map[120] === map[0]", "We're back at the start. From now on this will just loop the results.");
console.log("expected %i, got %i (different values/permutations in the results)", length, new Set(Object.values(map)).size);
.as-console-wrapper{top:0;max-height:100%!important}
You said without storing. I'm using the map above because this snippet would only store the last 50 console.logs while it shows all 120 entries/lines in the map. And to show at the end that it creates no duplicates, that there are indeed 120 different permutations in that map.
You could take a simplified approach and hand over just an array of indices and take two rules:
If the last element is greater then the previous element, swap both.
Search for an index from the end of the array where the element is greater than left and right element.
If found, search for the next grater element on the right side of the found index inclusive of the actual index, take this as new element in front of the group, sort the rest and apply.
If not found, end recursion.
function next([...array]) {
console.log(...array);
if (array[array.length - 2] < array[array.length - 1]) {
[array[array.length - 2], array[array.length - 1]] = [array[array.length - 1], array[array.length - 2]];
return next(array);
}
let index = array.length - 1;
while (--index) {
if (array[index - 1] < array[index] && array[index] > array[index + 1]) {
let value = Math.min(...array.slice(index - 1).filter(v => v > array[index - 1]))
array = [
...array.slice(0, index - 1),
value,
...array.slice(index - 1).filter(v => v !== value).sort((a, b) => a - b)
];
break;
}
}
if (!index) return;
return next(array);
}
next([0, 1, 2, 3, 4]);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Create a function to slice without using slice()

I am trying to write a function called slice that accepts an array and two numbers.
The function should return a new array with the elements starting at the index of the first number and going until the index of the second number.
If a third parameter is not passed to the function, it should slice until the end of the array by default.
If the third parameter is greater than the length of the array, it should slice until the end of the array.
function slice(s, n, m) {
let a = [];
a = s.splice(n, m);
if(m === undefined || m > s.length) {
a = s.splice(n, s.length);
}
return a;
}
let s = [1, 2, 3, 4, 5];
slice(s, 1, 7);
output []
UPDATE:
Thanks for everyone's help; I GOT IT!!! happy dance
function slice(arr, start, end) {
let result = [];
from = Math.max(start, 0);
to = Math.min(end);
if((!end) || (end > arr.length)) {
for(let i = from; i<arr.length; i++) {
result.push(arr[i]);}
} else {
for(let i = from; i<to; i++) {
result.push(arr[i]);
}
}
return result;
}
slice([1, 2, 3, 4, 5], 2, 4);
The main problem is that .splice mutates the array, so on your first call to it you remove a part of the array (or in your case the whole array). Therefore if the code enters the if, and you call .splice a second time, the array is already empty. An if / else would work so that .splice gets only called once.
But that would still then not replicate the behaviour of .slice, as .slice does not mutate the original array. Therefore you rather need a loop, that copies one element after the other:
// if "do" doesn't get passed, initialize with array.length (default parameter)
function slice(array, from, to = array.length) {
// make sure the bounds are within the range
from = Math.max(from, 0);
to = Math.min(to, array.length);
// initialize an array we can copy values into
const result = [];
for(let index = from; index < to; index++) {
// left as an exercise :)
}
return result;
}
Answering this since the OP said the time for the homework has passed.
One way to solve this problem is to have two pointers to second and third arguments. If you have all the arguments given, this is how you should start
start = n
end = m
// if m is greater than length of s or if m is not given
if(m == undefined || m > s.length()){
end = s.length() - 1;
}
then it is a simple for loop from start to end, both inclusive.
int[] result = new int[end-start+1];
for(int i = start; i <= end; i++){
result[j] = s[i];
}
Code may not be syntactically correct but you can fix that.

deleting duplicates on sorted array

Just in case you missed, the question is about deleting duplicates on a sorted array. Which can be applied very fast algorithms (compared to unsorted arrays) to remove duplicates.
You can skip this if you already know how deleting duplicates on SORTED arrays work
Example:
var out=[];
for(var i=0,len=arr.length-1;i<len;i++){
if(arr[i]!==arr[i+1]){
out.push(arr[i]);
}
}
out.push(arr[i]);
See?, it is very fast. I will try to explain what just happened.
The sorted arrays *could look like this:
arr=[0,1,1,2,2,3,4,5,5,6,7,7,8,9,9,9];
*the sorting could be ASC or DESC, or by other weird methods, but the important thing is that every duplicated item is next each other.
We stopped at array.length-1 because we don't have anything to check with
Then we added the last element regardless of anything because:
case A:
... ,9,9,9];//we have dup(s) on the left of the last element
case B:
... ,7,9,10];//we don't have dup(s) on the left of the last element
If you really understand what is happening, you will know that we haven't added any 9 on the case A. So because of that, we want to add the last element no matter if we are on case A or B.
Question:
That explained, I want to do the same, but ignoring the undefined value on cases like:
var arr=[];arr[99]=1;//0 through 98 are undefined, but do NOT hold the undefined value
I want to remove those. And on the case I have some real undefined values, these should not be removed.
My poor attempt is this one:
var out=[];
for (var i=0,len=arr.length; i < len - 1;) {
var x = false;
var y = false;
for (var j = i, jo; j < len - 1; j++) {
if (j in arr) {
x = true;
jo = arr[j];
i = j + 1;
break;
}
}
if (x == false) {
break;
}
for (var u = i, yo; u < len - 1; u++) {
if (u in arr) {
y = true;
yo = arr[u];
i = u + 1;
break;
}
}
if (y == false) {
out.push(jo);
break;
}
if (jo !== yo) {
out.push(jo);
}
}
out.push(arr[len - 1]);
I am really lost, any help is appreciated
A modern one-liner using .filter()
arr.filter((e, i, a) => e !== a[i - 1]);
I'm very surprised by the complexity of other answers here, even those that use .filter()
Even using old-school ES5 syntax with no arrow functions:
arr.filter(function (e, i, a) { return e !== a[i - 1] });
Example:
let a = [0, 1, 1, 2, 2, 3, 4, 5, 5, 6, 7, 7, 8, 9, 9, 9];
let b = arr.filter((e, i, a) => e !== a[i - 1]);
console.log(b); // [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
If you need to mutate the array in place then just use:
arr = arr.filter((e, i, a) => e !== a[i - 1]);
Personally I would recommend against using such complex solutions as the ones in other answers here.
For a start, I'm not entirely certain your original code is kosher. It appears to me that it may not work well when the original list is empty, since you try to push the last element no matter what. It may be better written as:
var out = [];
var len = arr.length - 1;
if (len >= 0) {
for (var i = 0;i < len; i++) {
if (arr[i] !== arr[i+1]) {
out.push (arr[i]);
}
}
out.push (arr[len]);
}
As to your actual question, I'll answer this as an algorithm since I don't know a lot of JavaScript, but it seems to me you can just remember the last transferred number, something like:
# Set up output array.
out = []
# Set up flag indicating first entry, and value of last added entry.
first = true
last = 0
for i = 0 to arr.length-1:
# Totally ignore undefined entries (however you define that).
if arr[i] is defined:
if first:
# For first defined entry in list, add and store it, flag non-first.
out.push (arr[i])
last = arr[i]
first = false
else:
# Otherwise only store if different to last (and save as well).
if arr[i] != last:
out.push (arr[i])
last = arr[i]
This is a one-liner:
uniquify( myArray.filter(function(x){return true}) )
If you don't already have uniquify written (the function you wrote to remove duplicates), you could also use this two-liner:
var newArray = [];
myArray.forEach(function(x) {
if (newArray.length==0 || newArray.slice(-1)[0]!==x)
newArray.push(x)
})
Elaboration:
var a=[];
a[0]=1; a[1]=undefined; a[2]=undefined;
a[10]=2; a[11]=2;
According to OP, array has "five elements" even though a.length==12. Even though a[4]===undefined, it is not an element of the array by his definition, and should not be included.
a.filter(function(x){return true}) will turn the above array into [1, undefined, undefined, 2, 2].
edit: This was originally written with .reduce() rather than .forEach(), but the .forEach() version is much less likely to introduce garbage-collector and pass-by-value issues on inefficient implements of javascript.
For those concerned about compatibility with the 6-year-old MIE8 browser, which does not support the last two editions of the ECMAScript standard (and isn't even fully compliant with the one before that), you can include the code at https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach However if one is that concerned about browser compatibility, one ought to program via a cross-compiler like GWT. If you use jQuery, you can also rewrite the above with only a few extra characters, like $.forEach(array, ...).
Perhaps something like this:
var out = [],
prev;
for(var i = 0; i < arr.length; i++) {
if (!(i in arr))
continue;
if (arr[i] !== prev || out.length === 0) {
out.push(arr[i]);
prev = arr[i];
}
}
The out.length check is to allow for the first defined array element having a value of undefined when prev also starts out initially as undefined.
Note that unlike your original algorithm, if arr is empty this will not push an undefined value into your out array.
Or if you have a new enough browser, you could use the Array.forEach() method, which iterates only over array elements that have been assigned a value.
An explicit way would be to pack the array (remove the undefined) values and use your existing algorithm for the duplicates on that..
function pack(_array){
var temp = [],
undefined;
for (i=0, len = _array.length; i< len; i++){
if (_array[i] !== undefined){
temp.push(_array[i]);
}
}
return temp;
}
I think this is what you want. It's a pretty simple algorithm.
var out = [], previous;
for(var i = 0; i < arr.length; i++) {
var current = arr[i];
if(!(i in arr)) continue;
if(current !== previous) out.push(current);
previous = arr[i];
}
This will run in O(N) time.
A very simple function, the input array must be sorted:
function removeDupes(arr) {
var i = arr.length - 1;
var o;
var undefined = void 0;
while (i > 0) {
o = arr[i];
// Remove elided or missing members, but not those with a
// value of undefined
if (o == arr[--i] || !(i in arr)) {
arr.splice(i, 1);
}
}
return arr;
}
It can probably be more concise, but might become obfuscated. Incidentally, the input array is modified so it doesn't need to return anything but it's probably more convenient if it does.
Here's a forward looping version:
function removeDupes2(arr) {
var noDupes = [],
o;
for (var i=0, j=0, iLen=arr.length; i<iLen; i++) {
o = arr[i];
if (o != noDupes[j] && i in arr) {
noDupes.push(o);
j = noDupes.length - 1;
}
}
return noDupes;
}
PS
Should work on any browser that supports javascript, without any additional libraries or patches.
This solution removes duplicates elements in-place. not recommended for functional programming
const arr =[0,0,1,1,2,2,2,3,4,5,5,6,7,7,8,9,9,9];
const removeDuplicates = (nums) => {
nums.forEach((element, idx) => {
nums.splice(idx, nums.lastIndexOf(element) - idx)
})
}
removeDuplicates(arr)
console.log(arr);
//sort the array
B.sort(function(a,b){ return a - b});
//removing duplicate characters
for(var i=0;i < B.length; i ++){
if(B[i]==B[i + 1])
B.splice(i,1)
}
if element in next index and current position is same remove the element at
current position
splice(targetPosition,noOfElementsToBeRemoved)
I believe what you are trying to achieve is not quite possible, but I could be wrong.
It's like one of those classic CS problems like the one where a barber in a village only shaves the one who don't shave themselves.
If you set the value of an array's index item as undefined, it's not really undefined.
Isn't that the case? A value can only be undefined when it hasn't been initialized.
What you should be checking for is whether a value is null or undefined. If null or duplicate skip the value, else retain it.
If null values and duplicates are what you are trying to skip then below function will do the trick.
function removeDuplicateAndNull(array){
if(array.length==0)
return [];
var processed = [], previous=array[0];
processed.push(array[0]);
for(var i = 1; i < array.length; i++) {
var value = array[i];
if( typeof value !== 'undefined' && value ==null)
continue;
if(value !== previous || typeof value === 'undefined')
processed.push(value);
previous = array[i];
}
return processed;
}
Test cases:
array=[,5,5,6,null,7,7] output =[ ,5,6,7]
array=[ 5,5,,6,null,,7,7] output=[5,,6,,7]
array=[7,7,,] output=[7,]
But even with this function there's a caveat. IF you check third test, the output is [7,]
instead of [7,,] !
If you check the length of the input and output arrays, array.length =3 and output.length=2.
The caveat is not with the function but with JavaScript itself.
This code is written in javascript. Its very simple.
Code:
function remove_duplicates(arr) {
newArr = [];
if (arr.length - 1 >= 0) {
for (i = 0; i < arr.length - 1; i++) {
// if current element is not equal to next
// element then store that current element
if (arr[i] !== arr[i + 1]) {
newArr.push(arr[i]);
}
}
newArr.push(arr[arr.length - 1]);
}
return newArr
}
arr=[0,1,1,2,2,3,4,5,5,6,7,7,8,9,9,9];
console.log(remove_duplicates(arr));
Here is the simple JavaScript solution without using any extra space.
function removeDuplicates(A) {
let i = 0;
let j = i + 1;
while (i < A.length && j < A.length) {
if (A[i] === A[j]) {
A.splice(i, 1);
j=i+1;
} else {
i++;
j++;
}
}
return A;
}
console.log('result', removeDuplicates([0,1,1,2,2,2,2,3,4,5,6,6,7]))
You can try the simple way
function hello(a: [], b: []) {
return [...a, ...b];
}
let arr = removeDuplicates(hello([1, 3, 7], [1, 5, 10]));
arr = removeDuplicates(arr);
function removeDuplicates(array) {
return array.filter((a, b) => array.indexOf(a) === b);
}
let mainarr = arr.sort((a, b) => parseInt(a) - parseInt(b));
console.log(mainarr); //1,3,5,7,10
One liner code
[1,3,7,1,5,10].filter((a, b) => [1,3,7,1,5,10].indexOf(a) === b).sort((a, b) => parseInt(a) - parseInt(b))
Here is simple solution to remove duplicates from sorted array.
Time Complexity O(n)
function removeDuplicate(arr) {
let i=0;
let newArr= [];
while(i < arr.length) {
if(arr[i] < arr[i+1]) {
newArr.push(arr[i])
} else if (i === (arr.length-1)) {
newArr.push(arr[i])
}
i++;
}
return newArr;
}
var arr = [1,2,3,4,4,5,5,5,6,7,7]
console.log(removeDuplicate(arr))
Let's suppose that you have a sorted array and you can't use additional array to find and delete duplicates:
In Python
def findDup(arr, index=1, _index=0):
if index >= len(arr):
return
if arr[index] != arr[_index]:
findDup(arr, index+1, _index+1)
if arr[index] == arr[_index]:
arr = deletedup(arr, index)
findDup(arr, index, _index) #Has to remain same here, because length has changed now
def deletedup(arr, del_index):
del arr[del_index]
return arr
arr = [1, 2, 3, 4, 4, 4, 5, 6, 7, 7, 7, 7, 7]
findDup(arr)
print arr

Categories

Resources