Skip to content

Commit bc4b1b1

Browse files
committed
remove a val in arr and return the length of remaining values
1 parent b77bd8b commit bc4b1b1

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed

removeelement/index.test.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
const { expect } = require("chai")
2+
const removeElement = require("./solution");
3+
4+
describe("remove element", () => {
5+
it("should remove an element and return its length", () => {
6+
/**
7+
* Assumptions being that,
8+
* an array is provided and not empty
9+
* the might be in the arr or not
10+
*/
11+
const result = removeElement([3, 2, 1, 3], 3);
12+
expect(result).to.equal(2);
13+
});
14+
15+
it("returns 4 when val is not in an arr below", () => {
16+
const result = removeElement([3, 2, 1, 3], 5);
17+
expect(result).to.equal(2);
18+
})
19+
});

removeelement/question.txt

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
-> Given an array arr and a value val,
2+
-> remove all instances of that value in-place
3+
-> and return the new length.
4+
5+
-> Do not allocate extra space for another array,
6+
-> you must do this by modifying the input array in-place with O(1) extra memory.
7+
8+
-> The order of elements can be changed.
9+
-> It doesn't matter what you leave beyond the new length.
10+
11+
Example:-
12+
13+
-> Given arr = [3,2,2,3], val = 3,
14+
-> Your function should return length = 2
15+
-> with the first two elements of arr being 2.
16+
-> It doesn't matter what you leave beyond the returned length.

removeelement/solution.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
const removeElement = (arr, val) => {
2+
// initialize count to zero
3+
let counts = 0;
4+
// loop through the arra
5+
for (let i = 0; i < arr.length; i++) {
6+
/**
7+
* check if num is not equal to val
8+
* then increment the number of counts
9+
* but assigining its num values
10+
*/
11+
if (nums[i] != val) {
12+
nums[counts++] = nums[i]
13+
}
14+
}
15+
// return our counts
16+
return counts;
17+
}
18+
19+
exports = module.exports = removeElement;

0 commit comments

Comments
 (0)