Create a function to slice without using slice() - javascript

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.

Related

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)];
}

Move array to the right, and make missing space 0

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);

DailyCodingProblem, find pair in array that matches a given value

I'm fairly new to coding and enlisted for the daily coding problem mailing list and got this question:
Given a list of numbers and a number k, return whether any two numbers
from the list add up to k.
My solution (after some stackoverflow digging) looks like this;
function problemOne_Solve()
{
const k = 17;
const values = [11, 15, 3, 8, 2];
for (i=0; i < values.length; i++) {
if ( values.find( (sum) => { return k-values[i] === sum} ) ) return true;
}
return false;
}
I'm wondering why it works. To me it looks like the part with the fat-arrow function closes the brackets inside the if statements conditional logic. And there is no such brackets after the if statement, which I thought was required.
I was also wondering how i would go about outputting the pair or pairs that sums up to "k," to build further on the solution. I would like to be able to display the pairs on the page for example.
.find takes a callback, which is invoked for every item in the array (or, up until a match is found). The first argument to the callback is the item being iterated over. If a match is found (if the return value from the callback was truthy for any element), the .find returns the item that resulted in a truthy return value.
So, on the first i = 0 iteration, and values[i] is 11, (sum) => { return k-values[i] === sum} will first check whether 17 - 11 === 11, and then whether 17 - 11 === 15, and then whether 17 - 11 = 3, etc.
This condition will generally be fulfilled if two numbers in the array add up to the k, but the algorithm is buggy. For example, an array composed of [1] will check the 1 against itself on the first iteration, adding up to 2:
function problemOne_Solve() {
const k = 2;
const values = [1];
for (i=0; i < values.length; i++) {
if ( values.find( (sum) => { return k-values[i] === sum} ) ) return true;
}
return false;
}
console.log(problemOne_Solve());
That is wrong. Another problem is that .find returns the found value. But, if the array is an array of numbers, the found value may be 0, and 0 is falsey. So the below example should return true because two elements sum up to 0 (0 and 0), but it returns false:
function problemOne_Solve() {
const k = 0;
const values = [0, 0];
for (i=0; i < values.length; i++) {
if ( values.find( (sum) => { return k-values[i] === sum} ) ) return true;
}
return false;
}
console.log(problemOne_Solve());
To get it right and decrease the computational complexity from O(n ^ 2) to O(n), iterate over the array once. Create an object whose keys are the numbers being iterated over, and on each iteration, check to see if a key of target - currNum exists on the object (where target is the target sum, and currNum is the current number from the array):
function problemOne_Solve() {
const target = 17;
const values = [11, 15, 3, 8, 2];
const obj = {};
for (const currNum of values) {
if (obj.hasOwnProperty(target - currNum)) {
return true;
}
obj[currNum] = true;
}
return false;
}
console.log(problemOne_Solve());
I was also wondering how i would go about outputting the pair or pairs that sums up to "k," to build further on the solution. I would like to be able to display the pairs on the page for example.
Instead of returning immediately when a match is found, push to an array and then return that array at the end of the function. Also, instead of setting the object values to true (or false), set them to the number of occurrences the number has been found so far (and decrement the matching number when a match is found):
function problemOne_Solve() {
const target = 17;
const values = [11, 15, 3, 8, 2, 17, 0, 0, 17];
const obj = {};
const matches = [];
for (const currNum of values) {
const otherNum = target - currNum;
if (obj[otherNum]) {
obj[otherNum]--;
matches.push([currNum, otherNum]);
}
obj[currNum] = (obj[currNum] || 0) + 1;
}
return matches;
}
console.log(problemOne_Solve());
And there is no such brackets after the if statement, which I thought was required.
Brackets are not required when there's a single statement after an if (or else if or else), eg:
if (true) console.log('true');
else console.log('this will not log');
And there is no such brackets after the if statement, which I thought was required.
If there is only one statement after if else the brackets becomes optional. Ideally you shouldn't write the if block is one line to make your code clean
As you are a beginner I would recommend you to use simple for loops instead of these fancy methods like find.
You can do that in following steps:
Its clear that you need sum of each element with every other element of array. So you will need a nested loop structure
The outer loop or main loop starts from 0 and loop till end of array.
You need to create a inner loop or nested loop which starts from index after the current index.
In the each iteration of nested loop you need to check if the sum of two elements is equal to requiredSum or not.
function pairWithSum(givenArray, requiredSum){
for(let i = 0; i < givenArray.length; i++){
for(let j = i + 1; j < givenArray.length; j++){
let sum = givenArray[i] + givenArray[j];
if(sum === requiredSum){
return [givenArray[i], givenArray[j]];
}
}
}
return false
}
console.log(pairWithSum([1, 4, 5, 8], 12));
console.log(pairWithSum([1, 4, 5, 8], 15));
I'm wondering why it works
That is because, if expects an expression/ statement to validate.
values.find( (sum) => { return k-values[i] === sum} )
This is a statement and it will be evaluated before and its output will be passed to if for condition.
Now Array.find has a return type: T|<null> where T is any value array is made of. So in second iteration, when values[i] refers to 15, it will return 2.
Now in JS, 2 is a truthy value and hence it goes inside if block. Foe more reference, check All falsey values in JavaScript. Any value that is not in this list will be considered as true.
My Javascript solution using JS object. This solution memories the elements when we go through the array which can be memory expensive. But the complexity will stay as O(n).
const checkTwoSum = (arr, sum) => {
const obj = {};
const found = arr?.find(item => {
const target = sum - item;
if (obj[target]) return true;
else {
obj[item] = 1;
}
});
return !!(found || found === 0);
}

Javascript for loop write to array undefined

Hi im doing the first part of eloquent javascript chp4 The Sum of a Range.
After spending some time i was sure i cracked the first part.
"Write a range function that takes two arguments, start and end,
and returns an array containing all the numbers from start
up to (and including) end."
I have looked at peoples answers but they all include the further parts of the question. I want to keep it simple, after all if i cant do the first part then there's no hope. it seems easy.
function range(start, end) {
let array = [];
for (let i = start; i <= end; i++){array.push(i);}
}
console.log(range(20 , 25));
but i get undefined, i have tried even copying and reducing the books answers to a similar situation.
It feels like my brain just cant do code. Where am i going wrong? Why is it undefined?
below is given answer
function range(start, end, step = start < end ? 1 : -1) {
let array = [];
if (step > 0) {
for (let i = start; i <= end; i += step) array.push(i);
} else {
for (let i = start; i >= end; i += step) array.push(i);
}
return array;
}
function sum(array) {
let total = 0;
for (let value of array) {
total += value;
}
return total;
}
console.log(range(1, 10))
// → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(range(5, 2, -1));
// → [5, 4, 3, 2]
console.log(sum(range(1, 10)));
// → 55
thx guys
You are not returning anything from range. Use return array; in range function:
function range(start, end) {
let array = [];
for (let i = start; i <= end; i++){array.push(i);}
return array;
}
console.log(range(20 , 25));
The variable array is declared with let which gives it block scope. It is declared inside the function range
function range(start, end) {
let array = [];
for (let i = start; i <= end; i++){array.push(i);}
}
and its duration expires when the function terminates. It does not exist anymore afterwards.
As others have already said, return array.
This way a reference is kept for the line where it is called. And if assigned to another reference there, the duration of the array will be extended until unreferenced. Then it goes to garbage collection.
Example:
let arr = range(5,10);
the code for eloquent java script can be like this:
function range(start,end,step){
let myArr=[];
if(step){
for(let i=start;i<=end;i+=step){
myArr.push(i);
}
return myArr;
}
else{
for(let i=start;i<=end;i++){
myArr.push(i);
}
return myArr;}
}
function sum(arr){
let total=0;
for (let item of arr){
total +=item;
}
return total;
}
sum(range(1,10,2));

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