Skip to content

[pull] master from amejiarosario:master #1

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
merged 1 commit into from
May 7, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 2 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ module.exports = {

// https://eslint.org/docs/rules/no-plusplus
// allows unary operators ++ and -- in the afterthought (final expression) of a for loop.
'no-plusplus': [2, { 'allowForLoopAfterthoughts': true }],
'no-plusplus': [0, { 'allowForLoopAfterthoughts': true }],
'no-continue': [0],

// Allow for..of
'no-restricted-syntax': [0, 'ForOfStatement'],
Expand Down
31 changes: 31 additions & 0 deletions lab/exercises/10-mixed/2sum-1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@

/**
* Given a SORTED array and a target, return the indices of the 2 number that sum up target
*
* @param {number[]} nums
* @param {numer} target
* @returns
*
* @runtime O(n)
*/
function twoSum(nums, target) {
const len = nums.length - 1;
let lo = 0;
let hi = len;

while (lo < hi && hi > 0 && lo < len) {
const sum = nums[lo] + nums[hi];
if (sum === target) {
return [lo, hi];
}
if (sum > target) {
hi--;
} else {
lo++;
}
}

return [];
}

module.exports = twoSum;
25 changes: 25 additions & 0 deletions lab/exercises/10-mixed/2sum.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

/**
* Given an array and a target, return the indices of the 2 number that sum up target
*
* @param {number[]} nums
* @param {numer} target
* @returns
*
* @runtime O(n)
*/
function twoSum(nums, target) {
const map = new Map();

for (let i = 0; i < nums.length; i++) {
const diff = target - nums[i];
if (map.has(diff)) {
return [map.get(diff), i];
}
map.set(nums[i], i);
}

return [];
}

module.exports = twoSum;
23 changes: 23 additions & 0 deletions lab/exercises/10-mixed/2sum.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const fn = require('./2sum');

describe('2 sum', () => {
it('should work', () => {
expect(fn([-1, 0, 1], 0)).toEqual(expect.arrayContaining([0, 2]));
});

it('should work', () => {
expect(fn([2, 7, 11, 15], 9)).toEqual([0, 1]);
});

it('should work', () => {
expect(fn([2, 7, 11, 15], 18)).toEqual([1, 2]);
});

it('should be empty', () => {
expect(fn([2, 7, 11, 15], 1)).toEqual([]);
});

it('should should work with non-sorted', () => {
expect(fn([3, 2, 4], 6)).toEqual([1, 2]);
});
});
29 changes: 29 additions & 0 deletions lab/exercises/10-mixed/3sum-1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* @param {number[]} nums
* @return {number[][]}
*
* @runtime O(n^3)
*/
function threeSum(nums) {
const ans = new Set();

for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
for (let k = j + 1; k < nums.length; k++) {
if (nums[i] + nums[j] + nums[k] === 0) {
ans.add(JSON.stringify([nums[i], nums[j], nums[k]].sort()));
}
}
}
}

return Array.from(ans).map((s) => JSON.parse(s));
}

module.exports = threeSum;

// Given an array find the unique triplets elements that sum zero.

// Brute force: O(n^3)
// Using twoSum: O(n^2)
//
47 changes: 47 additions & 0 deletions lab/exercises/10-mixed/3sum-2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/**
* @param {number[]} nums
* @return {number[][]}
*
* @runtime O(n^2)
* @space O(n)
*/
const threeSum = function (nums) {
const array = nums.reduce((acc, n, i) => { // O(n^2)
if (i > nums.length - 2) return acc;
const partial = twoSum(nums, -n, i + 1);
const res = partial.map((p) => [n, ...p]);
// console.log({i, n, partial, res, acc})
return acc.concat(res);
}, []);

// remove dups
const set = array.reduce((acc, n) => {
const str = n.sort((a, b) => a - b).toString();
return acc.add(str);
}, new Set());

// convert to array of nums
return [...set].map((a) => a.split(',').map((n) => +n));
};

function twoSum(nums, target, start) { // O(n)
const ans = [];
const map = new Map();

for (let i = start; i < nums.length; i++) {
if (map.has(target - nums[i])) {
ans.push([target - nums[i], nums[i]]);
}
map.set(nums[i], i);
}

return ans;
}

module.exports = threeSum;

// Given an array find the unique triplets elements that sum zero.

// Brute force: O(n^3)
// Using twoSum: O(n^2)
//
47 changes: 47 additions & 0 deletions lab/exercises/10-mixed/3sum.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/**
* @param {number[]} nums
* @return {number[][]}
*
* @runtime O(n^2) and skips duplicates
* @space O(1)
*/
function threeSum(nums) {
const ans = [];

nums.sort((a, b) => a - b); // sort: O(n log n)

for (let i = 0; i < nums.length - 2; i++) { // O(n^2)
if (i > 0 && nums[i - 1] === nums[i]) continue; // skip duplicates

let lo = i + 1;
let hi = nums.length - 1;

while (lo < hi) {
const sum = nums[i] + nums[lo] + nums[hi];
if (sum === 0) {
ans.push([nums[i], nums[lo], nums[hi]]);
// console.log([nums[i], nums[lo], nums[hi]]);
lo++;
hi--;
while (lo < hi && nums[lo - 1] === nums[lo]) lo++; // skip duplicates
while (lo < hi && nums[hi + 1] === nums[hi]) hi--; // skip duplicates
} else if (sum < 0) {
lo++;
while (lo < hi && nums[lo - 1] === nums[lo]) lo++; // skip duplicates
} else {
hi--;
while (lo < hi && nums[hi + 1] === nums[hi]) hi--; // skip duplicates
}
}
}

return ans;
}

module.exports = threeSum;

// Given an array find the unique triplets elements that sum zero.

// Brute force: O(n^3)
// Using twoSum: O(n^2)
//
44 changes: 44 additions & 0 deletions lab/exercises/10-mixed/3sum.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const fn = require('./3sum');

describe('3 Sum', () => {
it('should work', () => {
expect(fn([-1, 0, 1, 2, -1, 4])).toEqual(expect.arrayContaining([
expect.arrayContaining([-1, 0, 1]),
expect.arrayContaining([-1, 2, -1]),
]));
});

it('should work', () => {
const actual = fn([-2, 0, 1, 1, 2]);
expect(actual.length).toEqual(2);
expect(actual).toEqual(expect.arrayContaining([
expect.arrayContaining([-2, 0, 2]),
expect.arrayContaining([-2, 1, 1]),
]));
});

it('should work', () => {
const actual = fn([-2, -4, -2, -2, 0, 1, 2, 2, 2, 3, 3, 4, 4, 6, 6]);
expect(actual.length).toEqual(6);
expect(actual).toEqual(expect.arrayContaining([
expect.arrayContaining([-4, -2, 6]),
expect.arrayContaining([-4, 0, 4]),
expect.arrayContaining([-4, 1, 3]),
expect.arrayContaining([-4, 2, 2]),
expect.arrayContaining([-2, -2, 4]),
expect.arrayContaining([-2, 0, 2]),
]));
});

it('should work with many zeros', () => {
const actual = fn(Array(5).fill(0));
expect(actual.length).toEqual(1);
expect(JSON.stringify(actual)).toEqual('[[0,0,0]]'); // jest negative zero workaround
});

it('should work with large arrays', () => {
const actual = fn(Array(3000).fill(0));
expect(actual.length).toEqual(1);
expect(JSON.stringify(actual)).toEqual('[[0,0,0]]');
});
});
109 changes: 109 additions & 0 deletions lab/exercises/10-mixed/alien-dictionary.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@

/**
* Add nodes and edges into a graph using adjacency list
*
* @class Graph
*/
class Graph {
constructor() {
this.nodes = new Map();
}

// add node or directed edge
add(node1, node2) {
// console.log({node1, node2})
const adj = this.nodes.has(node1) ? this.nodes.get(node1) : new Set();
if (node2) adj.add(node2);
this.nodes.set(node1, adj);
}
}

/**
* DFS + tarjan for loop detection
*
* @param {Graph} g
* @param {Map} node
* @param {Set} set
* @param {Map} [parent=null]
* @param {Map} [grouping=new Map()]
* @param {number} [depth=0]
* @returns {boolean} true if has a loop, false otherwise
*/
function hasLoopOrAddToSet(g, node, set, parent = null, grouping = new Map(), depth = 0) {
if (set.has(node)) set.delete(node);
set.add(node);
grouping.set(node, depth);

// console.log({node, adjs: g.nodes.get(node)});

for (const adj of g.nodes.get(node)) {
// if (adj === parent) continue; // only for indirected graph

if (!grouping.has(adj)) {
if (hasLoopOrAddToSet(g, adj, set, node, grouping, depth + 1)) return true;
}

const minGroup = Math.min(grouping.get(adj), grouping.get(node));
grouping.set(node, minGroup);

if (grouping.get(adj) === grouping.get(node)) return true;
}
}


/**
* Find the order of the alien alphabet given a list of words on lexicographical order.
*
* @param {string[]} words
* @return {string} The alien alphabet order.
*/
function alienOrder(words) {
const g = new Graph();
if (!words || words.length < 2) return words && words.join('');

for (let i = 1; i < words.length; i++) { // O(n) * O(k)
const w1 = words[i - 1];
const w2 = words[i];
let j = 0;

while (j < w1.length && j < w2.length && w1[j] === w2[j]) { // O(k), k = max word length
g.add(w1[j++]);
}

if (j === w2.length && w1.length > w2.length) {
return ''; // shorter words should come first.
}

if (w1[j]) g.add(w1[j], w2[j]);
[...w1.slice(j)].forEach((n) => g.add(n));
[...w2.slice(j)].forEach((n) => g.add(n));
}

// console.log({ g: JSON.stringify(g) });
// console.log({ g: g.nodes });

const set = new Set();
for (const [node] of g.nodes) { // O(?)
if (hasLoopOrAddToSet(g, node, set)) { // DFS: O(E + V), V: total unique letters
return '';
}
}

return [...set].join('');
}

module.exports = alienOrder;

// Find the order of the alien alphabet given a list of words on lexicographical order.

// take words in pair, and build a dependency graph.
// skip while w1.char === w2.char
// add the first diff chars as a adj nodes
// add each letter as a node in the graph.

// find the order of the alien alph
// iterate over each node
// dfs + tarjan to detect loops
// add each visited node to a set
// if there’s a loop return ‘’
// return set
Loading