├── 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 | //