Skip to content

Commit 3fd2af3

Browse files
committed
updating large collection of popular problems with solutions
1 parent bd0588d commit 3fd2af3

File tree

243 files changed

+14081
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

243 files changed

+14081
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// returns things in array 'a' that are not in array 'b'
2+
// ['a','b','c','1', '2', '3'].complement(['b', 'c', 'd', 'e']);
3+
// ['a', '1', '2', '3']
4+
5+
complements = (arr1, arr2) => {
6+
7+
return (Array.isArray(arr1) && Array.isArray(arr2))
8+
? arr1.filter((elem) => arr2.indexOf(elem) === - 1)
9+
: undefined
10+
}
11+
12+
let arr1 = ['a','b','c','1', '2', '3'];
13+
let arr2 = ['b', 'c', 'd', 'e'];
14+
15+
console.log(complements(arr1, arr2)); // => [ 'a', '1', '2', '3' ]
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/* The problem here gives, by how many steps the array will be rotated, and NOT by how many positions the Array will be rotated.
2+
3+
A left rotation operation on an array of size shifts each of the array’s elements unit to the left. For example, if 2 left rotations are performed on array [1, 2, 3, 4, 5], then the array would become [3, 4, 5, 1, 2].
4+
5+
The tests expe
6+
7+
This solution, where a positive n rotates the array to the left, and a negative n to the right */
8+
9+
function leftRotateArray (array, rotationSteps) {
10+
// check if the array is long enough to rotate
11+
if (array.length < 2) {
12+
return array.slice(0);
13+
}
14+
// calculate the number of rotation to do.
15+
// But still we do this extra step, just to check if there's any need to rotate the array at all, with the code in the next line. Because, if I need to to rotate the array, 5000 times, it would take a while (code's O(n)). And in the end, the rotated array might be back where it started, making all those rotation pointless. So that seems like there are optimizations that can be made.
16+
var n = rotationSteps % array.length;
17+
18+
// Id n is 0, then no need to rotate at all, we can just return a copy of the array. And in this case of no rotation, the reason I am returning a copy instead of the original array (which could the code more optimized ) is because, the function should always return a copy in order to be consistent. If it sometimes doesn't, we don't know what you're getting.
19+
20+
if (n === 0) {
21+
return array.slice(0);
22+
}
23+
24+
/* A> n can be negative only when "rotationNumber" (i.e. the dividend) is negative. For example, if rotationNumber is -1, (i.e. the purpose is to pass a negative rotation-count to rotate right) then the n will be -1 and so array.slice will return offset from the end of the sequence. That is, array.slice(-1) extracts the last elements in the sequence OR array.slice(-4) extracts the last 4 elements of the array (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice)
25+
26+
B> Now, rotating an array is the same as chopping it into two pieces and putting them together "backwards".
27+
28+
C> So, when rotaionNumber is -4 and do n = -4 % 5 (i.e. -4), in the below , first we extract the last 4 elements of the array, then to that concat the first element (i.e. array.slice(0, array.length + (-4)) which is array.slice(0, 1) which is the first element)
29+
*/
30+
if (n < 0) {
31+
return array.slice(n).concat(array.slice(0, array.length+n));
32+
} else {
33+
return array.slice(n).concat(array.slice(0, n));
34+
}
35+
}
36+
37+
console.log(leftRotateArray([1, 2, 3, 4, 5], 19));
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
const { data } = require("./mongo-json-data-TEST");
2+
const moment = require("moment");
3+
4+
/* Problem Statement - From call to Mongo, I am getting the date field formatted according to Mongo's own formatting syntax. But after getting the raw data from Mongo, I shall format each of the date field to whatever formatting I need
5+
6+
The Performance test here, implements the problem from file - array-of-Objects-mutate-formatting-Mongo-date
7+
8+
9+
*/
10+
11+
/*
12+
The basic idea is to create a new empty object for each item in the array and assign the properties from old objects to them, respectively. This means we get an object with a new reference, so we are not going to modify the Original One.
13+
*/
14+
const doNotMutateOriginalArr = (arr) => {
15+
let mutatedArr = arr.map(e => {
16+
if (e.imported_date) {
17+
e = {
18+
...e,
19+
imported_date:
20+
moment(e.imported_date).format("MMM D, YYYY 12:00:00 ") + `AM`
21+
};
22+
}
23+
return e;
24+
});
25+
return mutatedArr
26+
}
27+
28+
// In this function, I am mutating the original array itself.
29+
30+
const mutateOriginalArr = (arr) => {
31+
arr.map(e => {
32+
if (e.imported_date) {
33+
e.date = moment(e.imported_date).format("MMM D, YYYY 12:00:00 ") + `AM`
34+
}
35+
return e;
36+
})
37+
return arr;
38+
}
39+
40+
// console.log(doNotMutateOriginalArr(data));
41+
// console.log(mutateOriginalArr(data));
42+
43+
44+
console.time("1st");
45+
doNotMutateOriginalArr(data)
46+
console.timeEnd("1st");
47+
48+
console.log("*******************************");
49+
50+
console.time("2nd");
51+
mutateOriginalArr(data)
52+
console.timeEnd("2nd");
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
/* Problem Statement - From call to Mongo, I am getting the date field formatted according to Mongo's own formatting syntax. But after getting the raw data from Mongo, I shall format each of the date field to whatever formatting I need.
2+
3+
*/
4+
const moment = require("moment");
5+
6+
// Original data that I will receive from Mongo
7+
const mongoData = [
8+
{
9+
_id: "5c77dc4c11ce1434b0029e7e",
10+
imported_commodity_objectId: {
11+
_id: "5c6c0f969c84ea3c7194a7de",
12+
name: "Ash",
13+
type: "Industrial Material",
14+
createdAt: "2019-02-19T14:15:50.690Z",
15+
updatedAt: "2019-02-19T14:15:50.690Z",
16+
__v: 0
17+
},
18+
qty_in_mts: 22,
19+
dateFromMongo: "2019-02-28T00:00:00.000Z",
20+
no_of_vessels_per_day: 223,
21+
createdAt: "2019-02-28T13:04:12.748Z",
22+
updatedAt: "2019-02-28T13:04:21.203Z",
23+
__v: 0
24+
},
25+
{
26+
_id: "5c77d37169e8d22c8a18e622",
27+
imported_commodity_objectId: {
28+
_id: "5c6c0f839c84ea3c7194a7dd",
29+
name: "Coal",
30+
type: "Minerals",
31+
createdAt: "2019-02-19T14:15:31.140Z",
32+
updatedAt: "2019-02-19T14:15:31.140Z",
33+
__v: 0
34+
},
35+
qty_in_mts: 55,
36+
dateFromMongo: "2019-02-27T18:30:00.000Z",
37+
no_of_vessels_per_day: 555,
38+
createdAt: "2019-02-28T12:26:25.488Z",
39+
updatedAt: "2019-02-28T12:26:33.223Z",
40+
__v: 0
41+
}
42+
];
43+
44+
/* Note, here I am NOT mutating the original array.
45+
The basic idea is to create a new empty object for each item in the array and assign the properties from old objects to them, respectively. This means we get an object with a new reference, so we are not going to modify the Original One.
46+
*/
47+
const mutatedMongoData = mongoData.map(e => {
48+
if (e.dateFromMongo) {
49+
e = {
50+
...e,
51+
dateFromMongo: moment(e.dateFromMongo).format("MMM D, YYYY 12:00:00 ") + `AM`
52+
};
53+
}
54+
return e;
55+
});
56+
57+
console.log(mutatedMongoData);
58+
59+
60+
/* Extremely important for React NOT TO MUTATE THE STATE
61+
62+
FROM BLOG POST - https://medium.freecodecamp.org/handling-state-in-react-four-immutable-approaches-to-consider-d1f5c00249d5
63+
64+
Imagine you have a form for editing a user. It’s common to create a single change handler to handle changes to all form fields. It may look something like this:
65+
66+
67+
```JS
68+
updateState(event) {
69+
const {name, value} = event.target;
70+
let user = this.state.user; // this is a reference, not a copy...
71+
user[name] = value; // so this mutates state 🙀
72+
return this.setState({user});
73+
}
74+
```
75+
76+
I’m using ES6 object shorthand on line 5 — you can omit the right-hand side when the left-hand side matches.
77+
78+
The concern is on line 4. Line 4 actually mutates state because the user variable is a reference to state. React state should be treated as immutable.
79+
80+
From the React docs:
81+
82+
Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.
83+
Why?
84+
85+
setState batches work behind the scenes. This means a manual state mutation may be overridden when setState is processed.
86+
If you declare a shouldComponentUpdate method, you can’t use a === equality check inside because the object reference will not change. So the approach above has a potential performance impact as well.
87+
Bottom line: The example above often works okay, but to avoid edge cases, treat state as immutable.
88+
89+
*/
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
const events = [
2+
{
3+
name: "First Event",
4+
metadata: {
5+
type: "public"
6+
}
7+
},
8+
{
9+
name: "Event 2",
10+
metadata: {
11+
type: "private"
12+
}
13+
},
14+
{
15+
name: "Third Event",
16+
metadata: {
17+
type: "closed"
18+
}
19+
}
20+
];
21+
22+
/* FROM BLOG POST - https://medium.freecodecamp.org/handling-state-in-react-four-immutable-approaches-to-consider-d1f5c00249d5
23+
24+
Note, here I am NOT mutating the original array.
25+
The basic idea is to create a new empty object for each item in the array and assign the properties from old objects to them, respectively. This means we get an object with a new reference, so we are not going to modify the Original One.
26+
*/
27+
const mappedEvents = events.map(e => {
28+
if (e.name) {
29+
e = { ...e, name: "Second Event Mutated" };
30+
}
31+
return e;
32+
});
33+
34+
console.log(mappedEvents);
35+
36+
/* OUTPUT -
37+
[ { name: 'Second Event Mutated', metadata: { type: 'public' } },
38+
{ name: 'Second Event Mutated', metadata: { type: 'private' } },
39+
{ name: 'Second Event Mutated', metadata: { type: 'closed' } } ]
40+
*/
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
/* Write a function that takes an array of integers and returns that array rotated by N positions.
2+
For example, if N=2, given the input array [1, 2, 3, 4, 5, 6] the function should return [5, 6, 1, 2, 3, 4] */
3+
4+
/* A> Rotating an array is the same as chopping it into two pieces and putting them together "backwards".
5+
6+
B> So, for rotation, chop this array into 2 pieces the last 3 elements, and the rest of the elements.
7+
8+
C> Now just bring those last 3 elements into first positon and concatenate the rest of the elements to this.
9+
*/
10+
11+
function rightRotate (array, k) {
12+
var L = array.length;
13+
return array.slice(L - k).concat(array.slice(0, L - k));
14+
};
15+
16+
console.log(rightRotate([1,2,3,4,5,6,7], 3));
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// Find the number in an array that is closest to a given number
2+
3+
// sort based on distance from the reference value num, and then take the first item.
4+
closestNumInArr = (arr, num) => {
5+
return arr.sort((a, b) => Math.abs(num - a) - Math.abs(num - b))[0];
6+
}
7+
8+
console.log(closestNumInArr([5,10,15,20,25,30,35], 22));
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/* Source Problem - https://youtu.be/E_hTGcx8o7g?t=3m24s - The Indian guy doing mock interview
2+
3+
Given an array containing multiple number of max elements - count the number of max elements.
4+
5+
so, given [ 1, 2, 2, 3, 4, 5, 4, 5]
6+
7+
I should return 2 as 5 occurs 2 times.
8+
*/
9+
10+
maxCount = arr => {
11+
12+
arr = arr.sort((a, b) => b - a);
13+
14+
let max = Math.max(...arr);
15+
16+
result = 0;
17+
18+
for (let i = 0; i < arr.length; i++ ) {
19+
if (max === arr[i]) {
20+
result++
21+
}
22+
if (arr[i] < max) break;
23+
}
24+
return result;
25+
}
26+
27+
28+
let myArr = [ 1, 2, 2, 3, 4, 5, 4, 5]
29+
30+
console.log(maxCount(myArr));

0 commit comments

Comments
 (0)