Skip to content

Commit 3022832

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

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed

Diff for: removeelement/index.test.js

+19
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+
const result = removeElement([3, 2, 1, 3], 3);
7+
expect(result).to.equal(2);
8+
});
9+
10+
it("returns 4 when val is not in an arr below", () => {
11+
const result = removeElement([3, 2, 1, 3], 5);
12+
expect(result).to.equal(4);
13+
});
14+
15+
it("should return 0 when arr is empty", () => {
16+
const result = removeElement([], 3);
17+
expect(result).to.equal(0);
18+
});
19+
});

Diff for: removeelement/question.txt

+16
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.

Diff for: removeelement/solution.js

+19
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 (arr[i] != val) {
12+
arr[counts++] = arr[i]
13+
}
14+
}
15+
// return our counts
16+
return counts;
17+
}
18+
19+
exports = module.exports = removeElement;

0 commit comments

Comments
 (0)