├── cloudy ├── gopher.png ├── go.mod ├── runner │ └── runner.go ├── go.sum ├── cloudy.go └── cloudy_test.go ├── islands.js ├── timer.go ├── smallestWindow.js ├── sum-square-diff.js ├── sundays.js ├── n-digit-fib.js ├── fib.js ├── .gitignore ├── waterTrapped.js ├── README.md ├── max-gap.js ├── trees.js ├── substring.js ├── maximumRectangle.js ├── sorting.js └── LICENSE /cloudy/gopher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fhinkel/twitch/HEAD/cloudy/gopher.png -------------------------------------------------------------------------------- /cloudy/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/andybons/cloudy 2 | 3 | require github.com/andybons/ascii v0.0.0-20190215043645-86f2bf67280b 4 | -------------------------------------------------------------------------------- /cloudy/runner/runner.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "net/http" 6 | 7 | "github.com/andybons/cloudy" 8 | ) 9 | 10 | func main() { 11 | http.HandleFunc("/", cloudy.MyFunc) 12 | log.Fatal(http.ListenAndServe(":8080", nil)) 13 | } 14 | -------------------------------------------------------------------------------- /islands.js: -------------------------------------------------------------------------------- 1 | // Given a 2d grid map of '1's (land) and '0's (water), count 2 | // the number of islands. An island is surrounded by water and is 3 | // formed by connecting adjacent lands horizontally or vertically. 4 | // You may assume all four edges of the grid are all surrounded by water. 5 | 6 | -------------------------------------------------------------------------------- /timer.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | func main() { 9 | t := time.Date(2019, 2, 19, 21, 0, 0, 0, time.UTC) 10 | for { 11 | left := time.Until(t) 12 | fmt.Printf("\r%02d min %02d sec", int(left.Minutes()), int(left.Seconds())%60) 13 | time.Sleep(1 * time.Second) 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /smallestWindow.js: -------------------------------------------------------------------------------- 1 | // Given two strings string1 and string2, 2 | // find the smallest substring in string1 containing all 3 | // characters of string2 efficiently. 4 | 5 | // Input : string = "this is a test string" 6 | // pattern = "tist" 7 | // Output : "t stri" 8 | 9 | // Input : string = "geeksforgeeks" 10 | // pattern = "ork" 11 | // Output : "ksfor" -------------------------------------------------------------------------------- /sum-square-diff.js: -------------------------------------------------------------------------------- 1 | // Difference between the sum of the 2 | // squares of the first one hundred natural 3 | // numbers and the square of the sum. 4 | 5 | 6 | let sumOfSquares = 0; 7 | let squareOfSums = 0; 8 | for(let i = 1; i <= 100; i++) { 9 | sumOfSquares += i*i; 10 | squareOfSums += i; 11 | } 12 | squareOfSums *= squareOfSums; 13 | 14 | console.log(squareOfSums - sumOfSquares); 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /cloudy/go.sum: -------------------------------------------------------------------------------- 1 | github.com/andybons/ascii v0.0.0-20190215043645-86f2bf67280b h1:9N1Ht24Ifk0BULn7C+reKLdkh5WEEb2IQ1POn0bRd5c= 2 | github.com/andybons/ascii v0.0.0-20190215043645-86f2bf67280b/go.mod h1:/pRnAttkHmGucexsXqXwvMf9dK3ZlTGnfrxEAVkMA38= 3 | github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ= 4 | github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8= 5 | -------------------------------------------------------------------------------- /sundays.js: -------------------------------------------------------------------------------- 1 | // 2 | 3 | const sundays = () => { 4 | // 1 Jan 1900 was a Monday. 5 | // 365, leap year 366 6 | 7 | let res = 0; 8 | for(let year = 1901; year <= 2000; year++) { 9 | for(let month = 0; month < 12; month++) { 10 | const day = new Date(year, month, 1).getDay(); 11 | if (day === 0) { 12 | res++; 13 | } 14 | } 15 | } 16 | console.log(res); 17 | } 18 | 19 | sundays() -------------------------------------------------------------------------------- /n-digit-fib.js: -------------------------------------------------------------------------------- 1 | 2 | 3 | function* fib() { 4 | let last = BigInt(1); 5 | let current = BigInt(1); 6 | 7 | yield last; 8 | yield current; 9 | 10 | while (true) { 11 | current += last; 12 | last = current - last; 13 | yield current; 14 | } 15 | } 16 | 17 | function nDigitFib() { 18 | let i = 1; 19 | for(const n of fib()) { 20 | if(n.toString().length === 1000) { 21 | console.log(i); 22 | break; 23 | } 24 | i++; 25 | } 26 | } 27 | 28 | 29 | nDigitFib(); -------------------------------------------------------------------------------- /cloudy/cloudy.go: -------------------------------------------------------------------------------- 1 | package cloudy 2 | 3 | import ( 4 | "fmt" 5 | "image" 6 | "net/http" 7 | "os" 8 | 9 | "github.com/andybons/ascii" 10 | 11 | _ "image/png" 12 | ) 13 | 14 | // MyFunc has a comment that makes linter happy 15 | func MyFunc(w http.ResponseWriter, r *http.Request) { 16 | w.Header().Set("Content-Type", "text/html; charset=utf-8") 17 | 18 | f, err := os.Open("gopher.png") 19 | if err != nil { 20 | http.Error(w, err.Error(), http.StatusInternalServerError) 21 | return 22 | } 23 | defer f.Close() 24 | 25 | src, _, err := image.Decode(f) 26 | if err != nil { 27 | http.Error(w, err.Error(), http.StatusInternalServerError) 28 | return 29 | } 30 | art := ascii.Thumbnail(src, 80, 80) 31 | fmt.Fprintf(w, `
%s
`, art) 32 | } 33 | -------------------------------------------------------------------------------- /cloudy/cloudy_test.go: -------------------------------------------------------------------------------- 1 | package cloudy 2 | 3 | import ( 4 | "io/ioutil" 5 | "net/http/httptest" 6 | "strings" 7 | "testing" 8 | ) 9 | 10 | func TestMyFunc(t *testing.T) { 11 | req := httptest.NewRequest("GET", "/", nil) 12 | w := httptest.NewRecorder() 13 | MyFunc(w, req) 14 | resp := w.Result() 15 | 16 | if got, want := resp.StatusCode, 200; got != want { 17 | t.Errorf("resp.StatusCode: got %d; want %d", got, want) 18 | } 19 | 20 | body, err := ioutil.ReadAll(resp.Body) 21 | if err != nil { 22 | t.Fatalf("ioutil.ReadAll: got unexpected error %v", err) 23 | } 24 | defer resp.Body.Close() 25 | 26 | if got, want := string(body), "....................,~+I7ZO88888888OZ7+"; !strings.HasPrefix(got, want) { 27 | t.Errorf("resp.Body: got %q; want %q ...", got, want) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /fib.js: -------------------------------------------------------------------------------- 1 | // Each new term in the Fibonacci sequence is generated 2 | // by adding the previous two terms. By starting 3 | // with 1 and 2, the first 10 terms will be: 4 | 5 | // 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... 6 | 7 | // By considering the terms in the Fibonacci sequence 8 | // whose values do not exceed four million, find the 9 | // sum of the even-valued terms. 10 | 11 | function* fib() { 12 | yield 2; 13 | 14 | let last = 1; 15 | let current = 2; 16 | 17 | while (true) { 18 | current = last + current; 19 | last = current - last; 20 | current = last + current; 21 | last = current - last; 22 | current = last + current; 23 | last = current - last; 24 | yield current; 25 | } 26 | } 27 | 28 | const fibSum = () => { 29 | let sum = 0; 30 | let gen = fib(); 31 | 32 | let current = gen.next().value; 33 | while (current <= 4000000) { 34 | sum += current + 1; 35 | current = gen.next().value 36 | } 37 | console.log(sum); 38 | } 39 | 40 | fibSum(); -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | # Logs 3 | logs 4 | *.log 5 | npm-debug.log* 6 | yarn-debug.log* 7 | yarn-error.log* 8 | 9 | # Runtime data 10 | pids 11 | *.pid 12 | *.seed 13 | *.pid.lock 14 | 15 | # Directory for instrumented libs generated by jscoverage/JSCover 16 | lib-cov 17 | 18 | # Coverage directory used by tools like istanbul 19 | coverage 20 | 21 | # nyc test coverage 22 | .nyc_output 23 | 24 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 25 | .grunt 26 | 27 | # Bower dependency directory (https://bower.io/) 28 | bower_components 29 | 30 | # node-waf configuration 31 | .lock-wscript 32 | 33 | # Compiled binary addons (https://nodejs.org/api/addons.html) 34 | build/Release 35 | 36 | # Dependency directories 37 | node_modules/ 38 | jspm_packages/ 39 | 40 | # TypeScript v1 declaration files 41 | typings/ 42 | 43 | # Optional npm cache directory 44 | .npm 45 | 46 | # Optional eslint cache 47 | .eslintcache 48 | 49 | # Optional REPL history 50 | .node_repl_history 51 | 52 | # Output of 'npm pack' 53 | *.tgz 54 | 55 | # Yarn Integrity file 56 | .yarn-integrity 57 | 58 | # dotenv environment variables file 59 | .env 60 | 61 | # next.js build output 62 | .next 63 | -------------------------------------------------------------------------------- /waterTrapped.js: -------------------------------------------------------------------------------- 1 | // Given n non-negative integers representing an 2 | // elevation map where the width of each bar is 1, compute 3 | // how much water it is able to trap after raining. 4 | 5 | // Input: [0,1,0,2,1,0,1,3,2,1,2,1] 6 | // Output: 6 7 | 8 | const leftMax = (a) => { 9 | const max = [a[0]]; 10 | for (let i = 1; i < a.length; i++) { 11 | max[i] = Math.max(max[i - 1], a[i]); 12 | } 13 | return max; 14 | } 15 | 16 | // O(n) 17 | const water = (a) => { 18 | let w = 0; 19 | const lefts = leftMax(a); 20 | const rights = leftMax(a.slice().reverse()).reverse(); 21 | for (let i = 0; i < a.length; i++) { 22 | const waterHeight = Math.min(lefts[i], rights[i]); 23 | w += waterHeight - a[i]; 24 | } 25 | return w; 26 | } 27 | 28 | 29 | // constantSpace 30 | const trappedWater = (a) => { 31 | if(a.length < 3) { 32 | return 0; 33 | } 34 | let water = 0; 35 | let left = 0; 36 | let right = a.length - 1; 37 | let leftMax = 0; 38 | let rightMax = 0; 39 | while (left < right) { 40 | if (a[left] < a[right]) { 41 | const height = Math.min(leftMax, rightMax); 42 | water += Math.max(0, height - a[left]); 43 | left++; 44 | leftMax = Math.max(a[left], leftMax); 45 | } else { 46 | const height = Math.min(leftMax, rightMax); 47 | water += Math.max(0, height - a[right]); 48 | right--; 49 | rightMax = Math.max(a[right], rightMax); 50 | } 51 | } 52 | 53 | return water; 54 | } 55 | 56 | 57 | const test = (a) => { 58 | let linear = water(a); 59 | let constant = trappedWater(a); 60 | if (linear !== constant) { 61 | console.log(a); 62 | console.log(linear, constant) 63 | throw new Error(a); 64 | } 65 | } 66 | 67 | test([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]); 68 | test([0, 1, 0, 2, 2, 4, 6, 3, 1, 8, 9, 1, 0, 1, 3, 2, 1, 2, 1]); 69 | test([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]); 70 | test([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]); -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Code samples from [twitch.tv/fhinkel](twitch.tv/fhinkel) 2 | 3 | # Sorting 4 | Video: [https://www.youtube.com/watch?v=oZyomw_N70o](https://www.youtube.com/watch?v=oZyomw_N70o) 5 | 6 | Code: [max-gap.js](https://github.com/fhinkel/twitch/blob/master/max-gap.js) 7 | 8 | ### The Maximum Gap Problem 9 | Given an unsorted array of numbers, find the maximum difference 10 | between the successive elements in its sorted form. 11 | Linear time (and linear space)! 12 | 13 | # Binary trees 14 | Video: [https://www.youtube.com/watch?v=vpOUP4jQqJM](https://www.youtube.com/watch?v=vpOUP4jQqJM) 15 | 16 | Code: [trees.js](https://github.com/fhinkel/twitch/blob/master/trees.js) 17 | 18 | * Tree traversals: inorder, preorder, and postorder. 19 | * Given a binary tree in which each node element contains a number. Find the maximum possible sum from one leaf node to nother. 20 | 21 | # Substrings, Subsequences, and Generators 22 | 23 | Video: [https://www.youtube.com/watch?v=sNvHfgm1yw0&t=9s](https://www.youtube.com/watch?v=sNvHfgm1yw0&t=9s) 24 | 25 | Code: [substring.js](https://github.com/fhinkel/twitch/blob/master/substring.js) 26 | 27 | Given a string s and an array of words, find that longest word 28 | that's a substring of s. 29 | 30 | # Leetcode, Codewars, Project Euler 31 | 32 | Video: [https://youtu.be/SiL6GmE0tTc](https://www.youtube.com/watch?v=SiL6GmE0tTc&list=PL65pp6Tpk690178KuYvWGSOnBAkDEBanD&index=6) 33 | 34 | Random selection of problems: 35 | 36 | * Number of Islands, [https://leetcode.com/problems/number-of-islands/](https://leetcode.com/problems/number-of-islands/) 37 | * Jewels and Stones, [https://leetcode.com/problems/jewels-and-stones/](https://leetcode.com/problems/jewels-and-stones/) 38 | * Vowel Count, [https://www.codewars.com/kata/54ff3102c1bad923760001f3](https://www.codewars.com/kata/54ff3102c1bad923760001f3) 39 | * Even Fibonacci Numbers, [https://projecteuler.net/problem=2](https://projecteuler.net/problem=2) 40 | * Sum Square Difference, [https://projecteuler.net/problem=6](https://projecteuler.net/problem=6) 41 | * 1000-Digit Fibonacci Number, [https://projecteuler.net/problem=25](https://projecteuler.net/problem=25) 42 | * Counting Sundays, [https://projecteuler.net/problem=19](https://projecteuler.net/problem=19) 43 | 44 | [//]: # (I'm solving typical coding problems you would be asked to solve during an interview. These puzzles are a lot of fun and there's always something new to learn.**Today's problem** Given an unsorted array, find the maximum difference between the successive elements in its sorted form.) 45 | 46 | [//]: # (👩💻I'm solving typical coding problems you would be asked to solve during an interview. ✨💻These puzzles are a lot of fun and there's always something new to learn. ✨🐢🚀✨) 47 | 48 | [//]: # (💻✨Node.js/JavaScript Interview training 👩‍💻🤓 📺Fun puzzles ✨🐢🚀✨!whatamidoing) -------------------------------------------------------------------------------- /max-gap.js: -------------------------------------------------------------------------------- 1 | // Video: https://www.youtube.com/watch?v=oZyomw_N70o 2 | 3 | // Given an unsorted array of numbers, find the maximum difference 4 | // between the successive elements in its sorted form. 5 | // Linear time (and linear space)! 6 | 7 | // Runtime complexity is n*log(n) 8 | const maxGapNLogN = input => 9 | input 10 | .sort((a, b) => a - b) 11 | .reduce((acc, cur, idx, src) => Math.max(acc, idx > 0 ? cur - src[idx - 1] : 0), 0); 12 | 13 | 14 | // linear time complexity 15 | const maxGap = (arr) => { 16 | const n = arr.length; 17 | let min = Number.POSITIVE_INFINITY; 18 | let max = Number.NEGATIVE_INFINITY; 19 | for (let i = 0; i < n; i++) { 20 | min = Math.min(arr[i], min); 21 | max = Math.max(arr[i], max); 22 | } 23 | 24 | let range = max - min; 25 | let lowerBound = range / (n - 1); 26 | 27 | let buckets = []; // n-1 buckets => linear space complexity 28 | for (let i = 0; i < n; i++) { 29 | let index = Math.floor((arr[i] - min) / lowerBound); 30 | if (!buckets[index]) { 31 | buckets[index] = {}; 32 | buckets[index].left = arr[i]; 33 | buckets[index].right = arr[i]; 34 | } else { 35 | if (buckets[index].left > arr[i]) { 36 | buckets[index].left = arr[i] 37 | } 38 | if (buckets[index].right < arr[i]) { 39 | buckets[index].right = arr[i] 40 | } 41 | } 42 | } 43 | 44 | let maxDiff = 0; 45 | let prev = min; 46 | for (let i = 0; i < buckets.length; i++) { 47 | if (!buckets[i]) { 48 | continue; 49 | } 50 | if (buckets[i].left - prev > maxDiff) { 51 | maxDiff = buckets[i].left - prev; 52 | } 53 | prev = buckets[i].right; 54 | } 55 | 56 | return maxDiff; 57 | } 58 | 59 | const randomInput = (n) => { 60 | let arr = []; 61 | for (let i = 0; i < n; i++) { 62 | arr.push((Math.random() > 0.5 ? 1 : -1) * (Math.random() * 100000)); 63 | } 64 | return arr; 65 | } 66 | 67 | const test = (arr) => { 68 | if (maxGapNLogN(arr) !== maxGap(arr)) { 69 | console.log(arr); 70 | console.log(`Expected ${maxGapNLogN(arr)} to equal ${maxGap(arr)}`); 71 | throw new Error(); 72 | } 73 | } 74 | 75 | test(randomInput(20)); 76 | test(randomInput(200)); 77 | test(randomInput(2000)); 78 | 79 | const perfTest = (n) => { 80 | console.log(`Array with ${n} elements:`) 81 | let arr = randomInput(n); 82 | let before = Date.now(); 83 | maxGapNLogN(arr); 84 | let after = Date.now(); 85 | console.log(`n log(n) takes ${(after - before) / 1000} seconds`); 86 | 87 | before = Date.now(); 88 | maxGap(arr); 89 | after = Date.now(); 90 | console.log(`Linear takes ${(after - before) / 1000} seconds`); 91 | console.log(); 92 | } 93 | 94 | perfTest(10); 95 | perfTest(100); 96 | perfTest(1000); 97 | perfTest(10000); 98 | perfTest(5000000); 99 | perfTest(10000000); 100 | perfTest(20000000); 101 | 102 | 103 | 104 | test([-1, 0, 10]); 105 | test([2, 6, 8]); 106 | test([-2, 6, -8]); 107 | test([20, 1, 17, 3, 16, 2, 7]); 108 | test([-20, 1, 17, -3, 16, 2, 7]); 109 | test([20, 1.1, 17, 3.5, -16, 2, 7]); 110 | test([]); 111 | test([2]); 112 | test([21, 41, 17, 45, 9, 17]); 113 | 114 | if (maxGapNLogN([2, 6, 8]) !== 4) { 115 | throw new Error(); 116 | } 117 | if (maxGapNLogN([20, 1, 17, 3, 16, 2, 7]) !== 9) { 118 | console.log(maxGapNLogN([20, 1, 17, 3, 16, 2, 7])); 119 | throw new Error(); 120 | } 121 | if (maxGapNLogN([-20, 1, 17, -3, 16, 2, 7]) !== 17) { 122 | throw new Error(); 123 | } 124 | if (maxGapNLogN([20, 1.1, 17, 3.5, -16, 2, 7]) !== 17.1) { 125 | throw new Error(); 126 | } 127 | if (maxGapNLogN([20]) !== 0) { 128 | throw new Error(); 129 | } 130 | if (maxGapNLogN([]) !== 0) { 131 | throw new Error(); 132 | } 133 | if (maxGapNLogN([5, 7]) !== 2) { 134 | console.log(maxGapNLogN([5, 7])) 135 | throw new Error(); 136 | } 137 | 138 | 139 | -------------------------------------------------------------------------------- /trees.js: -------------------------------------------------------------------------------- 1 | let node = { 2 | val: 6, 3 | left: null, 4 | right: null 5 | } 6 | 7 | const root = { val: 6 }; 8 | root.left = { val: 4 }; 9 | root.right = { val: 3 }; 10 | root.left.left = { val: -9 }; 11 | root.left.right = { val: 1 }; 12 | root.right.right = { val: 8 }; 13 | root.left.left.left = { val: 100 }; 14 | 15 | // 6 16 | // / \ 17 | // 4 3 18 | // /\ \ 19 | // -9 1 8 20 | // / 21 | // 100 22 | 23 | // Given a binary tree in which each node 24 | // element contains a number. Find the maximum 25 | // possible sum from one leaf node to another. 26 | 27 | const maxSumUntilNode = (node, currentMax) => { 28 | if (!node) { 29 | return 0; 30 | } 31 | if (!node.left && !node.right) { 32 | return node.val; 33 | } 34 | if (node.left && node.right) { 35 | const maxLeft = maxSumUntilNode(node.left, currentMax); 36 | const maxRight = maxSumUntilNode(node.right, currentMax); 37 | currentMax.val = Math.max(currentMax.val, maxLeft + maxRight + node.val); 38 | return Math.max(maxLeft, maxRight) + node.val; 39 | } 40 | if (!node.left) { 41 | return maxSumUntilNode(node.right, currentMax) + node.val; 42 | } 43 | if (!node.right) { 44 | return maxSumUntilNode(node.left, currentMax) + node.val; 45 | } 46 | } 47 | 48 | const maxSum = (root) => { 49 | if (!root || !root.left || !root.right) { 50 | return Number.NEGATIVE_INFINITY; 51 | } 52 | let max = { val: Number.NEGATIVE_INFINITY }; 53 | 54 | maxSumUntilNode(root, max); 55 | return max.val; 56 | } 57 | 58 | console.log(maxSum(root)); 59 | 60 | 61 | // Traversing the tree 62 | // Iterative, breadth-first search, level order traversal [6, 4, 3, 9, 1, null, 8] 63 | // Recursive, depth-first search 64 | // [6, 4, 9, 1, 3, null, 8] pre order 65 | // [9, 4, 1 , 6, null, 3, 8] in order 66 | // [9, 1, 4, null, 8, 3, 6] post order 67 | 68 | 69 | 70 | // // Inorder 71 | // const inorder = (node) => { 72 | // if (node === undefined) { 73 | // return; 74 | // } 75 | // inorder(node.left); 76 | // console.log(node.val); 77 | // inorder(node.right); 78 | // } 79 | // inorder(root); 80 | 81 | // // Preorder 82 | // const preorder = (node) => { 83 | // if (node === undefined) { 84 | // return; 85 | // } 86 | // console.log(node.val); 87 | // preorder(node.left); 88 | // preorder(node.right); 89 | // } 90 | // preorder(root); 91 | 92 | // // Postorder 93 | // const postorder = (node) => { 94 | // if (node === undefined) { 95 | // return; 96 | // } 97 | // postorder(node.left); 98 | // postorder(node.right); 99 | // console.log(node.val); 100 | // } 101 | // postorder(root); 102 | 103 | // // Level Order Traversal 104 | // const levelOrder = (root) => { 105 | // const queue = []; 106 | 107 | // queue.push(root); 108 | // while (queue.length !== 0) { 109 | // const node = queue.shift(); 110 | // if (node === undefined) { 111 | // continue; 112 | // } 113 | // console.log(node.val); 114 | // queue.push(node.left, node.right); 115 | // } 116 | // } 117 | 118 | // levelOrder(root); 119 | 120 | // Given inorder and postorder traversal of a tree, construct the binary tree. 121 | // const inorderInput = [9,3,15,20,7] 122 | // const postorderInput = [9,15,7,20,3] // left, right, parent 123 | 124 | // 3 125 | // / \ 126 | // 9 20 127 | // /\ 128 | // 15 7 129 | 130 | const makeTree = (inorder, postorder) => { 131 | if (inorder.length === 0) { 132 | return null; 133 | } 134 | let val = postorder[postorder.length - 1]; // last entry 135 | let index = inorder.indexOf(val); 136 | 137 | const root = { val }; 138 | 139 | root.left = makeTree(inorder.slice(0, index), postorder.slice(0, index)); 140 | root.right = makeTree(inorder.slice(index + 1), postorder.slice(index, -1)); 141 | 142 | return root; 143 | } 144 | 145 | const tree = makeTree([9, 3, 15, 20, 7], [9, 15, 7, 20, 3]); 146 | console.log(tree); 147 | 148 | // Given a singly linked list where elements are 149 | // sorted in ascending order, convert it to a height balanced BST. 150 | // For this problem, a height-balanced binary tree 151 | // is defined as a binary tree in which the depth 152 | // of the two subtrees of every node never differ by more than 1. 153 | // Given the sorted linked list: [-10,-3,0,5,9], 154 | // -10 155 | // \ 156 | // -3 157 | // \ 158 | // 0 159 | // \ 160 | // 5 161 | // \ 162 | // 9 163 | 164 | // 0 165 | // / \ 166 | // -3 5 167 | // / \ 168 | // -10 9 169 | 170 | // 0 171 | // / \ 172 | // -3 9 173 | // / / 174 | // -10 5 175 | 176 | 177 | // -3 178 | // / \ 179 | // -10 5 180 | // / \ 181 | // 0 9 182 | 183 | // 5 184 | // / \ 185 | // -3 9 186 | // / \ 187 | // -10 0 188 | // Solution: https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree 189 | 190 | 191 | 192 | 193 | 194 | 195 | // Find the maximum distance 196 | 197 | 198 | -------------------------------------------------------------------------------- /substring.js: -------------------------------------------------------------------------------- 1 | // Given a string s and an array of words, find that longest word 2 | // that's a substring of s. 3 | 4 | // Word w is a subsequence of s if some number of characters, possibly 5 | // zero, can be deleted from s to form w, without 6 | // reordering the remaining characters. 7 | 8 | // s = "abppplee" and 9 | // words = {"able", "ale", "apple", "bale", "kangaroo"} 10 | // the correct output would be "apple" 11 | 12 | // Assumption [a-z] 13 | 14 | const s = "abppplee"; 15 | const words = ["able", "ale", "apple", "bale", "kangaroo"]; 16 | 17 | 18 | 19 | // n number of letters in s 20 | // O(w*log(w) + n*w) 21 | const longestSubSequenceRegExp = (s, words) => { 22 | 23 | const isSubSequence = (s, word) => { 24 | // 'abc' => 'a.*b.*c' 25 | const match = s.match(word.split('').join('.*')); 26 | return match ? true : false; 27 | } 28 | 29 | // O(w*log(w)) - w number of words 30 | words.sort((a, b) => (b.length - a.length)); 31 | 32 | for (const word of words) { 33 | if (isSubSequence(s, word)) { 34 | return word; 35 | } 36 | } 37 | return ''; 38 | } 39 | 40 | // O(w*log(w) + n*w) 41 | const longestSubSequence = (s, words) => { 42 | 43 | const isSubSequence = (s, word) => { 44 | let index = -1; 45 | for (const char of word) { 46 | index = s.indexOf(char, index); 47 | if (index === -1) { 48 | return false; 49 | } 50 | } 51 | return true; 52 | } 53 | 54 | // O(w*log(w)) - w number of words 55 | words.sort((a, b) => (b.length - a.length)); 56 | 57 | for (const word of words) { 58 | if (isSubSequence(s, word)) { 59 | return word; 60 | } 61 | } 62 | return ''; 63 | } 64 | 65 | function* gen(left, right) { 66 | if (left.length === 0) { 67 | yield right; 68 | return; 69 | } 70 | 71 | let char = left.slice(-1); 72 | yield* gen(left.slice(0, -1), char + right); 73 | yield* gen(left.slice(0, -1), right); 74 | } 75 | 76 | 77 | const longestExponential = (s, words) => { 78 | let substrings = []; 79 | const allSubStrings = gen(s, ''); 80 | for (const substring of allSubStrings) { 81 | if (words.includes(substring)) { 82 | substrings.push(substring); 83 | } 84 | } 85 | substrings.sort((a, b) => b.length - a.length); 86 | return substrings.length > 0 ? substrings[0] : ''; 87 | } 88 | 89 | 90 | const longestSubSequencePreprocessed = (s, words) => { 91 | 92 | const buildIndexesByChar = (s) => { 93 | // 94 | let m = new Map(); 95 | let o = {}; 96 | for ("👀" = 0; o["👀"] < s.length; o["👀"]++) { 97 | o["🔱"] = s[o["👀"]]; 98 | o["🧠"] = m.get(o["🔱"]) || []; 99 | o["☃️"] = o["👀"] - o["🧠"].length + 1; 100 | m.set(o["🔱"], [...o["🧠"], ...Array(o["☃️"]).fill(o["👀"])]); // eyes and brains 101 | } 102 | return m; 103 | } 104 | 105 | const isSubSequence = (word, m) => { 106 | let index = 0; 107 | for (const char of word) { 108 | let idxs = m.get(char) || []; 109 | index = idxs[index]; 110 | 111 | if (index === undefined) { 112 | return false; 113 | } 114 | } 115 | return true; 116 | } 117 | 118 | let m = buildIndexesByChar(s); 119 | words.sort((a, b) => (b.length - a.length)); 120 | 121 | for (const word of words) { 122 | if (isSubSequence(word, m)) { 123 | return word; 124 | } 125 | } 126 | return ''; 127 | } 128 | 129 | const test = (f, s, words, expected) => { 130 | const res = f(s, words); 131 | if (res !== expected) { 132 | console.log(`${res} != ${expected}`); 133 | throw new Error(); 134 | } 135 | } 136 | 137 | test(longestSubSequence, s, words, 'apple'); 138 | test(longestSubSequenceRegExp, s, words, 'apple'); 139 | test(longestSubSequence, 'sfkjwfpbhadslsegsfd', words, 'bale'); 140 | test(longestSubSequence, 'sfkjwfpbhaasdfjlwefkjasdfwfasdfwefdslsegsfdxxx', ['afwefasfd', 'rgisd'], 'afwefasfd'); 141 | test(longestSubSequence, '', words, ''); 142 | test(longestSubSequence, s, [], ''); 143 | test(longestSubSequence, s, ['xxxx'], ''); 144 | test(longestSubSequence, s, [s, ...words], s); 145 | 146 | 147 | test(longestSubSequencePreprocessed, s, words, 'apple'); 148 | test(longestSubSequencePreprocessed, 'sfkjwfpbhadslsegsfd', words, 'bale'); 149 | test(longestSubSequencePreprocessed, 'sfkjwfpbhaasdfjlwefkjasdfwfasdfwefdslsegsfdxxx', ['afwefasfd', 'rgisd'], 'afwefasfd'); 150 | test(longestSubSequencePreprocessed, '', words, ''); 151 | test(longestSubSequencePreprocessed, s, [], ''); 152 | test(longestSubSequencePreprocessed, s, ['xxxx'], ''); 153 | test(longestSubSequencePreprocessed, s, [s, ...words], s); 154 | 155 | test(longestExponential, s, words, 'apple'); 156 | // test(longestExponential, 'sfkjwfpbhadslsegsfd', words, 'bale'); 157 | // test(longestExponential, 'sfkjwfpbhaasdfjlwefkjasdfwfasdfwefdslsegsfd', ['afwefasfd', 'rgisd'], 'afwefasfd'); 158 | test(longestExponential, '', words, ''); 159 | test(longestExponential, s, [], ''); 160 | test(longestExponential, s, ['xxxx'], ''); 161 | test(longestExponential, s, [s, ...words], s); -------------------------------------------------------------------------------- /maximumRectangle.js: -------------------------------------------------------------------------------- 1 | // Given n non-negative integers representing 2 | // the histogram's bar height where the width of each bar is 1, find 3 | // the area of largest rectangle in the histogram. 4 | 5 | // Input: [2,1,5,6,2,3] 6 | // Output: 10 7 | const { performance } = require('perf_hooks'); 8 | 9 | // O(n^3) 10 | const largestRectangle = (a) => { 11 | let maxArea = 0; 12 | for (let left = 0; left < a.length; left++) { 13 | for (let right = left; right < a.length; right++) { 14 | let min = Number.POSITIVE_INFINITY; 15 | for (let i = left; i <= right; i++) { 16 | min = Math.min(min, a[i]); 17 | } 18 | let area = min * (right - left + 1); 19 | maxArea = Math.max(area, maxArea); 20 | } 21 | } 22 | return maxArea; 23 | } 24 | 25 | // O(n^2) 26 | const largestRectangleQuad = (a) => { 27 | let maxArea = 0; 28 | for (let i = 0; i < a.length; i++) { 29 | const h = a[i]; 30 | let left = i; 31 | while (left >= 0) { 32 | if (a[left] < h) { 33 | break; 34 | } 35 | left--; 36 | } 37 | let right = i; 38 | while (right < a.length) { 39 | if (a[right] < h) { 40 | break; 41 | } 42 | right++; 43 | } 44 | const area = h * (right - left - 1); 45 | maxArea = Math.max(maxArea, area); 46 | } 47 | return maxArea; 48 | } 49 | 50 | 51 | // Given an array of integers, find the nearest smaller number for every 52 | // element such that the smaller element is on left side. 53 | const nearestSmallerLeft = (a) => { 54 | const res = []; 55 | const stack = []; 56 | stack.peek = () => { 57 | return stack[stack.length - 1]; 58 | } 59 | 60 | for (let i = 0; i < a.length; i++) { 61 | while (stack.length !== 0 && a[stack.peek()] >= a[i]) { 62 | stack.pop(); 63 | } 64 | if (stack.length === 0) { 65 | res.push(-1); 66 | } else { 67 | res.push(stack.peek()); 68 | } 69 | stack.push(i); 70 | } 71 | 72 | return res; 73 | } 74 | 75 | 76 | const nearestSmallerRight = (a) => { 77 | const res = []; 78 | const stack = []; 79 | stack.peek = () => { 80 | return stack[stack.length - 1]; 81 | } 82 | 83 | for (let i = a.length - 1; i >= 0; i--) { 84 | while (stack.length !== 0 && a[stack.peek()] >= a[i]) { 85 | stack.pop(); 86 | } 87 | if (stack.length === 0) { 88 | res.push(a.length); 89 | } else { 90 | res.push(stack.peek()); 91 | } 92 | stack.push(i); 93 | } 94 | 95 | return res.reverse(); 96 | } 97 | 98 | console.log(nearestSmallerLeft([2, 1, 5, 6, 2, 3])); 99 | console.log(nearestSmallerRight([2, 1, 5, 6, 2, 3])); 100 | 101 | // O(n) 102 | const largestRectangleLin = (a) => { 103 | let maxArea = 0; 104 | const leftNearest = nearestSmallerLeft(a); 105 | const rightNearest = nearestSmallerRight(a); 106 | for (let i = 0; i < a.length; i++) { 107 | const h = a[i]; 108 | let left = leftNearest[i]; 109 | let right = rightNearest[i]; 110 | const area = h * (right - left - 1); 111 | maxArea = Math.max(maxArea, area); 112 | } 113 | return maxArea; 114 | } 115 | 116 | console.log(largestRectangleLin([2, 1, 5, 6, 2, 3])); 117 | 118 | 119 | console.log(largestRectangle([2, 1, 5, 6, 2, 3])); // 10 120 | console.log(largestRectangle([2, 1, 0, 6, 2, 3])); //6 121 | console.log(largestRectangle([2, 1, 0, 8, 2, 3])); //8 122 | console.log(largestRectangle([2, 1, 0, 6, 2, 2, 2, 2, 2, 2])); //14 123 | // n = 1000, 1000000000 124 | 125 | console.log(largestRectangleQuad([2, 1, 5, 6, 2, 3])); // 10 126 | console.log(largestRectangleQuad([2, 1, 0, 6, 2, 3])); //6 127 | console.log(largestRectangleQuad([2, 1, 0, 8, 2, 3])); //8 128 | console.log(largestRectangleQuad([2, 1, 0, 6, 2, 2, 2, 2, 2, 2])); //14 129 | // n = 1000, 1000000 130 | 131 | console.log(largestRectangleLin([2, 1, 5, 6, 2, 3])); // 10 132 | console.log(largestRectangleLin([2, 1, 0, 6, 2, 3])); //6 133 | console.log(largestRectangleLin([2, 1, 0, 8, 2, 3])); //8 134 | console.log(largestRectangleLin([2, 1, 0, 6, 2, 2, 2, 2, 2, 2])); //14 135 | // n = 1000, 1000 136 | 137 | const test = (a) => { 138 | let before = performance.now(); 139 | let quad = largestRectangleQuad(a); 140 | let after = performance.now(); 141 | let seconds = Math.floor((after - before) / 1000); 142 | 143 | console.log(`Quadratic for ${a.length} elements took ${seconds} seconds.`); 144 | 145 | before = performance.now(); 146 | let cube = largestRectangleLin(a); 147 | after = performance.now(); 148 | seconds = Math.floor((after - before) / 1000); 149 | console.log(`Linear for ${a.length} elements took ${seconds} seconds.`); 150 | 151 | if (quad !== cube) { 152 | console.log(`${a}, ${quad} != ${cube}`); 153 | throw new Error(); 154 | } 155 | console.log('done') 156 | } 157 | 158 | const randomArray = (n) => { 159 | let a = []; 160 | for (let i = 0; i < n; i++) { 161 | a.push(Math.floor(Math.random() * 1000)); 162 | } 163 | return a; 164 | } 165 | 166 | test([2, 1, 5, 6, 2, 3]); 167 | test([2, 1, 22, 4, 3, 1, 6, 2, 4, 2, 4, 65, 6, 2, 3]); 168 | test(randomArray(20)); 169 | test(randomArray(3000)); 170 | test(randomArray(2000000)); 171 | 172 | 173 | 174 | 175 | 176 | 177 | -------------------------------------------------------------------------------- /sorting.js: -------------------------------------------------------------------------------- 1 | // Mergesort, Quicksort, Heapsort 2 | 3 | const testSort = (a, f) => { 4 | const original = a.slice(); 5 | const res = f(a).slice(); 6 | a.sort((a, b) => a - b); 7 | if (res.length !== a.length) { 8 | console.log(`${original} got sorted as ${res}`); 9 | throw new Error(); 10 | } 11 | for (let i = 0; i < a.length; i++) { 12 | if (res[i] !== a[i]) { 13 | console.log(`${original} got sorted as ${res}`); 14 | throw new Error(); 15 | } 16 | } 17 | console.log(res); 18 | } 19 | 20 | const testBogoSort = (a) => { 21 | const original = [...a]; 22 | const res = [...bogoSort(a)]; 23 | a.sort((a, b) => a - b); 24 | for (let i = 0; i < res.length; i++) { 25 | if (res[i] !== a[i]) { 26 | console.log(`${original} got sorted as ${res}`); 27 | throw new Error(); 28 | } 29 | } 30 | console.log(res); 31 | } 32 | 33 | const bogoSort = (a) => { 34 | const isSorted = (a) => { 35 | let prev = Number.NEGATIVE_INFINITY; 36 | for (let i = 0; i < a.length; i++) { 37 | if (a[i] < prev) { 38 | return false; 39 | } 40 | prev = a[i]; 41 | } 42 | return true; 43 | } 44 | 45 | const shuffle = (a) => { 46 | for (let i = a.length - 1; i > 0; i--) { 47 | const j = Math.floor(Math.random() * (i + 1)); 48 | [a[i], a[j]] = [a[j], a[i]]; 49 | } 50 | return a; 51 | } 52 | 53 | while (!isSorted(a)) { 54 | a = shuffle(a); 55 | } 56 | return a; 57 | } 58 | 59 | // Merge two sorted arrays 60 | const merge = (sortedLeft, sortedRight) => { 61 | let res = []; 62 | let i = 0; 63 | let j = 0; 64 | while (i < sortedLeft.length && j < sortedRight.length) { 65 | if (sortedLeft[i] < sortedRight[j]) { 66 | res.push(sortedLeft[i]); 67 | i++; 68 | } else { 69 | res.push(sortedRight[j]); 70 | j++; 71 | } 72 | } 73 | while (j < sortedRight.length) { 74 | res.push(sortedRight[j]); 75 | j++; 76 | } 77 | while (i < sortedLeft.length) { 78 | res.push(sortedLeft[i]); 79 | i++; 80 | } 81 | return res; 82 | } 83 | 84 | const testMergeFunction = (left, right) => { 85 | let a = [...left, ...right]; 86 | a.sort((a, b) => a - b); 87 | let res = merge(left, right); 88 | for (let i = 0; i < a.length; i++) { 89 | if (a[i] !== res[i]) { 90 | console.log(`Yikes, ${left}, ${right} got merged into ${res}`); 91 | throw new Error(); 92 | } 93 | } 94 | // console.log(res); 95 | } 96 | 97 | const mergeSort = (a) => { 98 | if (a.length < 2) { 99 | return a; 100 | } 101 | 102 | let middle = Math.floor(a.length / 2); 103 | let sortedLeft = mergeSort(a.slice(0, middle)); 104 | let sortedRight = mergeSort(a.slice(middle)); 105 | return merge(sortedLeft, sortedRight); 106 | } 107 | 108 | class Heap { 109 | constructor() { 110 | this.elements = []; 111 | } 112 | 113 | // 1 114 | // 2 3 115 | // 45 67 116 | // 89 1011 1213 1415 117 | // child of i: 2*i, 2*i+1 118 | 119 | 120 | // 0 121 | // 1 2 122 | // 34 56 123 | // 78 910 1112 1314 124 | 125 | bubbleup(i) { 126 | let parent = Math.floor((i - 1) / 2); 127 | const a = this.elements; 128 | while (parent >= 0 && a[parent] > a[i]) { 129 | [a[parent], a[i]] = [a[i], a[parent]]; 130 | i = parent; 131 | parent = Math.floor((i - 1) / 2); 132 | } 133 | } 134 | 135 | push(e) { 136 | this.elements.push(e); 137 | this.bubbleup(this.size() - 1); 138 | } 139 | 140 | sinkdown(i) { 141 | const leftChild = i * 2 + 1; 142 | const rightChild = i * 2 + 2; 143 | const a = this.elements; 144 | let swap = null; 145 | if (leftChild < this.size() && a[leftChild] < a[i]) { 146 | swap = leftChild; 147 | } 148 | if (rightChild < this.size() && a[rightChild] < (swap ? a[leftChild] : a[i])) { 149 | swap = rightChild; 150 | } 151 | if (!swap) { 152 | return; 153 | } 154 | [a[i], a[swap]] = [a[swap], a[i]]; 155 | 156 | this.sinkdown(swap); 157 | } 158 | 159 | pop() { 160 | if (this.size() === 0) { 161 | throw new Error('Cannot pop on empty heap'); 162 | } 163 | let min = this.elements[0]; 164 | let last = this.elements.pop(); 165 | 166 | if (this.size() > 0) { 167 | this.elements[0] = last; 168 | this.sinkdown(0); 169 | } 170 | 171 | return min; 172 | } 173 | 174 | size() { 175 | return this.elements.length; 176 | } 177 | } 178 | 179 | const heapSort = (a) => { 180 | let res = []; 181 | let heap = new Heap(); 182 | a.forEach(e => heap.push(e)); 183 | while (heap.size() !== 0) { 184 | res.push(heap.pop()); 185 | } 186 | return res; 187 | } 188 | 189 | testSort([2], mergeSort); 190 | testSort([], mergeSort); 191 | testSort([1, 2, 3, 4], mergeSort); 192 | testSort([5, 3, 8, 3, 5, 1, 1, 89, 17], mergeSort) 193 | testSort([5, -13, 8, 3, 42, 100000, 5, -1, 1, 89, 17], mergeSort) 194 | 195 | testSort([2], heapSort); 196 | testSort([], heapSort); 197 | testSort([1, 2, 3, 4], heapSort); 198 | testSort([1, 2, 3, 4, 5, 8, 9, 12, 13, 15, 16], heapSort); 199 | testSort([5, 3, 8, 3, 5, 1, 1, 89, 17], heapSort) 200 | testSort([5, -13, 8, 3, 42, 100000, 5, -1, 1, 89, 17], heapSort) 201 | 202 | testBogoSort([2]); 203 | testBogoSort([]); 204 | testBogoSort([1, 2, 3, 4]); 205 | // testBogoSort([5, 3, 8, 3, 5, 1, 1, 89, 17]) 206 | // testBogoSort([5, -13, 8, 3, 42, 100000, 5, -1, 1, 89, 17]) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------