Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[pull] master from amejiarosario:master #16

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
pull merged 11 commits into lalittolani:master from amejiarosario:master
Aug 22, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
11 commits
Select commit Hold shift + click to select a range
2fab838
add config test
amejiarosario Aug 20, 2020
4d75825
chore(jest): fix commands
amejiarosario Aug 20, 2020
b5a00dd
feat(book:array): add solutions for interview questions
amejiarosario Aug 20, 2020
996f7aa
chore(vscode): set colors
amejiarosario Aug 20, 2020
ca119f2
feat(book): add appendix D with interview question solutions
amejiarosario Aug 20, 2020
57960e2
fix(book): multiple broken links and bump epub version
amejiarosario Aug 21, 2020
5935b95
feat(book/array): add max subarray questions and solution
amejiarosario Aug 21, 2020
6ab8bc4
feat(book/array): add stock questions and solution
amejiarosario Aug 21, 2020
dbdef21
fix(book): workaround for c++ issue in asciidoc
amejiarosario Aug 22, 2020
9b356d9
Merge pull request #67 from amejiarosario/feat/add-exercises-solutions
amejiarosario Aug 22, 2020
e573929
:bookmark: chore(release): 1.11.0
semantic-release-bot Aug 22, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
feat(book/array): add max subarray questions and solution
  • Loading branch information
amejiarosario committed Aug 21, 2020
commit 5935b95ea761402b296e5a4fbd6e3643714bcaf9
40 changes: 25 additions & 15 deletions book/D-interview-questions-solutions.asc
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -6,32 +6,42 @@
=== Solutions for Array Questions
(((Interview Questions Solutions, Arrays)))

==== Rotate Left
include::content/part02/array.asc[tag=array-q-rotate-left]
==== Max Subarray [[array-q-max-subarray]]
include::content/part02/array.asc[tag=array-q-max-subarray]

We are asked to rotate an array multiple times (`k`).
The first step, is making sure we understand the problem well. Let's do a basic examples:

One brute force solution, would be removing the first element and appending it to the end `k` times:
----
A = [-5, 6, 9, -8]
B = [-1, 6, -3, 8]
----

What's the subarrays with the maximum sum? For A, it will be `[6, 9]` and for B it will be `[6, -3, 8]`.

One intution could be to generate all possible subarrays, add them up and then pick the max number.

[source, javascript]
----
include::interview-questions/rotate-array-left.js[tag=bruteForce]
include::interview-questions/max-subarray.js[tag=maxSubArrayBrute1]
----

However, what would happen if the array is huge (millions of elements)?
How efficient will be if `k` number is large (thousands)?

When k is bigger than the array, it will loop back over and over again. We can avoid extra computation by calculating the final place using modulus.
This is a simple to understand however not very efficient. The runtime is `O(n^3)`.

Here's the final solution:
If you noticed we adding up the numbers from `i` to `j` on each cycle. But, we can optimize this. We can keep a local variable and add the new number to it. That way we don't have to revisit previous numebers again.

[source, javascript]
----
include::interview-questions/rotate-array-left.js[tag=description]
include::interview-questions/rotate-array-left.js[tag=solution]
include::interview-questions/max-subarray.js[tag=maxSubArrayBrute2]
----

It runs on `O(n^2)` while the brute force solution was doing `O(n^2 * k)`.
The runtime is much better: `O(n)`. Can we still do better?

We can use a greedy approach, where do one pass through the array. We only add the numbers if their sum is larger than just taking the current element.

[source, javascript]
----
include::interview-questions/max-subarray.js[tag=description]
include::interview-questions/max-subarray.js[tag=solution]
----

==== Sum
include::content/part02/array.asc[tag=array-sum]
The runtime is `O(n)`! and a space complexity of `O(1)`.
33 changes: 8 additions & 25 deletions book/content/part02/array.asc
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ ifndef::imagesdir[]
endif::[]

[[array]]
=== Array
=== Array [[array-chap]]
(((Array)))
(((Data Structures, Linear, Array)))
Arrays are one of the most used data structures. You probably have used it a lot but are you aware of the runtimes of `splice`, `shift`, `indexOf` and other operations? In this chapter, we are going deeper into the most common operations and their runtimes.
Expand Down Expand Up @@ -279,35 +279,18 @@ To sum up, the time complexity of an array is:
==== Interview Questions
(((Interview Questions, Arrays)))

// tag::array-q-rotate-left[]
1) Implement an efficient algorithm that rotate an array `a` an `k` number of times.
===== Max Subarray
// tag::array-q-max-subarray[]
Given an array of integers, find the maximum sum of consecutive elements (subarray).
// end::array-q-max-subarray[]

[source, javascript]
----
include::../../interview-questions/rotate-array-left.js[tag=description]
include::../../interview-questions/max-subarray.js[tag=description]
// write you code here
}
----
// end::array-q-rotate-left[]

// tag::array-sum[]
2) Implement an algorithm that takes two arrays of numbers and return a new array with the sum.
_Solution: <<array-q-max-subarray>>_

[source, javascript]
----
/**
* Return the sum of two arrays as a new array.
*
* @example
* sum([1,2,3], [1,1,1]); // [2,3,4]
* sum([1], [9,9,9]); // [1,0,0,0]
*
* @param {number[]} a - Array of numbers.
* @param {number[]} b - Array of numbers.
* @returns {number[]} the sum array.
*/
function sum(a, b) {
// write you code and test with examples
}
----
// end::array-sum[]
// https://leetcode.com/problemset/algorithms/?topicSlugs=array
1 change: 1 addition & 0 deletions book/interview-questions/max-subarray.data.js
View file Open in desktop

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

54 changes: 54 additions & 0 deletions book/interview-questions/max-subarray.js
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// tag::description[]
/**
* Find the maximun sum of contiguous elements in an array.
* @examples
* maxSubArray([1, -3, 10, -5]); // => 10
* maxSubArray([-3,4,-1,2,1,-5]); // => 6
* @param {number[]} a - Array
*/
function maxSubArray(a) {
// end::description[]
// tag::solution[]
let max = -Infinity;
let local = 0;

a.forEach((n) => {
local = Math.max(n, local + n);
max = Math.max(max, local);
});

return max;
}
// end::solution[]

// tag::maxSubArrayBrute1[]
function maxSubArrayBrute1(nums) {
let max = -Infinity;

for (let i = 0; i < nums.length; i++) { // O(n^3)
for (let j = i + 1; j <= nums.length; j++) { // O(n^2)
const sum = nums.slice(i, j).reduce((a, n) => n + a, 0); // O(n)
max = Math.max(max, sum); // O(1)
}
}

return max;
}
// end::maxSubArrayBrute1[]

// tag::maxSubArrayBrute2[]
function maxSubArrayBrute2(nums) {
let max = -Infinity;

for (let i = 0; i < nums.length; i++) { // O(n) * O(n)
let local = 0;
for (let j = i; j < nums.length; j++) { // O(n)
local += nums[j];
max = Math.max(max, local);
}
}
return max;
}
// end::maxSubArrayBrute2[]

module.exports = { maxSubArrayBrute1, maxSubArrayBrute2, maxSubArray };
16 changes: 16 additions & 0 deletions book/interview-questions/max-subarray.spec.js
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const { maxSubArray, maxSubArrayBrute1, maxSubArrayBrute2 } = require('./max-subarray');
const largeArray = require('./max-subarray.data');

describe('Max Subarray Sum', () => {
[maxSubArray, maxSubArrayBrute1, maxSubArrayBrute2].forEach((fn) => {
describe(`with ${fn.name}`, () => {
it('should work with small arrays', () => {
expect(fn([-2, 1, -3, 4, -1, 2, 1, -5, 4])).toEqual(6);
});

it('should work with large arrays', () => {
expect(fn(largeArray)).toEqual(4853);
});
});
});
});
19 changes: 0 additions & 19 deletions book/interview-questions/rotate-array-left.spec.js
View file Open in desktop

This file was deleted.

23 changes: 23 additions & 0 deletions lab/exercises/01-arrays/rotate-array-left.spec.js
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const { rotateLeft, rotateLeftBruteForce } = require('./rotate-array-left');

const largeArray = Array(1e6).fill(1).map((t) => t * Math.random());

[rotateLeft, rotateLeftBruteForce].forEach((fn) => {
xdescribe(`Rotate Left ${fn.name}`, () => {
describe('when data is small', () => {
it('should work with 1', () => {
expect(fn([1, 2, 3], 1)).toEqual([2, 3, 1]);
});

it('should work with 4', () => {
expect(fn([1, 2, 3, 4, 5], 4)).toEqual([5, 1, 2, 3, 4]);
});
});

xdescribe('when data is large', () => {
it('should work at scale', () => {
expect(fn(largeArray, 75863)).toEqual(largeArray);
});
});
});
});
4 changes: 2 additions & 2 deletions package.json
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
"src/**/*.js"
],
"scripts": {
"test": "jest",
"watch": "jest --watch --coverage",
"test": "jest --verbose",
"watch": "jest --watch --verbose --coverage",
"coverage": "jest --coverage && open coverage/lcov-report/index.html",
"coverage:win": "jest --coverage && cmd.exe /C start coverage/lcov-report/index.html",
"lint": "npx eslint --fix --format codeframe src/",
Expand Down

AltStyle によって変換されたページ (->オリジナル) /