├── front-end ├── networking.md ├── caching.md ├── design.md ├── html.md ├── performance.md ├── widgets.md ├── browser.md ├── css.md ├── javascript.md ├── dom.md ├── security.md └── accessibility.md ├── .travis.yml ├── design ├── search-engine.md ├── README.md ├── collaborative-editor.md └── news-feed.md ├── algorithms ├── heap.md ├── geometry.md ├── bit-manipulation.md ├── queue.md ├── oop.md ├── hash-table.md ├── stack.md ├── graph.md ├── permutation.md ├── linked-list.md ├── sorting-searching.md ├── math.md ├── interval.md ├── dynamic-programming.md ├── topics.md ├── tree.md ├── matrix.md ├── array.md └── string.md ├── utilities ├── python │ ├── tree_mirror.py │ ├── tree_equal.py │ ├── is_subsequence.py │ ├── char_prime_map.py │ ├── graph_dfs.py │ ├── graph_topo_sort.py │ ├── union_find.py │ ├── tree_traversal.py │ ├── rabin_karp_hash.py │ ├── heap.py │ ├── quick_select.py │ ├── binary_search.py │ ├── trie.py │ └── linked_list.py └── javascript │ ├── treeMirror.js │ ├── treeEqual.js │ ├── matrixTranspose.js │ ├── isSubsequence.js │ ├── binToInt.js │ ├── matrixClone.js │ ├── intToBin.js │ ├── intervalsMerge.js │ ├── intervalsIntersect.js │ ├── binarySearch.js │ ├── matrixTraverse.js │ ├── graphTopoSort.js │ ├── deepEqual.js │ └── mergeSort.js ├── .editorconfig ├── domain ├── databases.md ├── networking.md ├── software-engineering.md ├── async-loading │ └── index.html ├── snake-game │ └── snake-game.md ├── security.md ├── pagination-sorting │ └── index.html └── tic-tac-toe │ └── index.html ├── non-technical ├── cover-letter.md ├── psychological-tricks.md ├── self-introduction.md ├── questions-to-ask.md ├── interview-formats.md ├── negotiation.md └── behavioral.md ├── LICENSE ├── interviewers └── basics.md ├── CODE_OF_CONDUCT.md ├── README.md ├── assets └── book.svg └── preparing └── cheatsheet.md /front-end/networking.md: -------------------------------------------------------------------------------- 1 | Networking 2 | == 3 | 4 | WIP. 5 | 6 | ## Glossary 7 | 8 | - **JSON** 9 | - **RPC** 10 | - **HTTP** 11 | - **HTTP/2** 12 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | install: 2 | - gem install awesome_bot 3 | 4 | script: 5 | - awesome_bot **/*.md --allow-dupe --allow-redirect --allow 429 --skip-save-results 6 | -------------------------------------------------------------------------------- /design/search-engine.md: -------------------------------------------------------------------------------- 1 | Search Engine 2 | == 3 | 4 | ###### References 5 | 6 | - [How Do Search Engines Work?](http://www.makeuseof.com/tag/how-do-search-engines-work-makeuseof-explains/) 7 | -------------------------------------------------------------------------------- /algorithms/heap.md: -------------------------------------------------------------------------------- 1 | Heap 2 | == 3 | 4 | - Merge `K` sorted lists together into a single list. 5 | - Given a stream of integers, write an efficient function that returns the median value of the integers. 6 | -------------------------------------------------------------------------------- /utilities/python/tree_mirror.py: -------------------------------------------------------------------------------- 1 | def tree_mirror(node): 2 | if not node: 3 | return 4 | node.left, node.right = node.right, node.left 5 | tree_mirror(node.left) 6 | tree_mirror(node.right) 7 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | trim_trailing_whitespace = true 7 | 8 | [*.{js,py}] 9 | charset = utf-8 10 | indent_style = space 11 | indent_size = 4 12 | -------------------------------------------------------------------------------- /utilities/javascript/treeMirror.js: -------------------------------------------------------------------------------- 1 | function treeMirror(node) { 2 | if (!node) { 3 | return; 4 | } 5 | let temp = node.left; 6 | node.left = node.right; 7 | node.right = temp; 8 | treeMirror(node.left); 9 | treeMirror(node.right); 10 | } 11 | -------------------------------------------------------------------------------- /domain/databases.md: -------------------------------------------------------------------------------- 1 | Databases 2 | == 3 | 4 | ## General 5 | 6 | - How should you store passwords in a database? 7 | - http://www.geeksforgeeks.org/store-password-database/ 8 | - https://nakedsecurity.sophos.com/2013/11/20/serious-security-how-to-store-your-users-passwords-safely/ 9 | -------------------------------------------------------------------------------- /domain/networking.md: -------------------------------------------------------------------------------- 1 | Networking 2 | == 3 | 4 | - Given an IPv4 IP address p and an integer n, return a list of CIDR strings that most succinctly represents the range of IP addresses from p to (p + n). 5 | - Describe what happens when you enter a url in the web browser. 6 | - Define UDP/TCP and give an example of both. 7 | -------------------------------------------------------------------------------- /utilities/python/tree_equal.py: -------------------------------------------------------------------------------- 1 | def tree_equal(node1, node2): 2 | if not node1 and not node2: 3 | return True 4 | if not node1 or not node2: 5 | return False 6 | return node1.val == node2.val and \ 7 | tree_equal(node1.left, node2.left) and \ 8 | tree_equal(node1.right, node2.right) 9 | -------------------------------------------------------------------------------- /algorithms/geometry.md: -------------------------------------------------------------------------------- 1 | Geometry 2 | == 3 | 4 | - You have a plane with lots of rectangles on it, find out how many of them intersect. 5 | - Which data structure would you use to query the k-nearest points of a set on a 2D plane? 6 | - Given many points, find k points that are closest to the origin. 7 | - How would you triangulate a polygon? 8 | -------------------------------------------------------------------------------- /utilities/javascript/treeEqual.js: -------------------------------------------------------------------------------- 1 | function treeEqual(node1, node2) { 2 | if (!node1 && !node2) { 3 | return true; 4 | } 5 | if (!node1 || !node2) { 6 | return false; 7 | } 8 | return node1.val == node2.val && 9 | treeEqual(node1.left, node2.left) && 10 | treeEqual(node1.right, node2.right); 11 | } 12 | -------------------------------------------------------------------------------- /algorithms/bit-manipulation.md: -------------------------------------------------------------------------------- 1 | Bit Manipulation 2 | == 3 | 4 | - How do you verify if an interger is a power of 2? 5 | - Write a program to print the binary representation of an integer. 6 | - Write a program to print out the number of 1 bits in a given integer. 7 | - Write a program to determine the largest possible integer using the same number of 1 bits in a given number. 8 | -------------------------------------------------------------------------------- /non-technical/cover-letter.md: -------------------------------------------------------------------------------- 1 | Cover Letter 2 | == 3 | 4 | - A short introduction describing who you are and what you're looking for. 5 | - What projects have you enjoyed working on? 6 | - Which have you disliked? What motivates you? 7 | - Links to online profiles you use (GitHub, Twitter, etc). 8 | - A description of your work history (whether as a resume, LinkedIn profile, or prose). 9 | -------------------------------------------------------------------------------- /utilities/python/is_subsequence.py: -------------------------------------------------------------------------------- 1 | def is_subsequence(s, t): 2 | """ 3 | :type s: str 4 | :type t: str 5 | :rtype: bool 6 | """ 7 | if len(s) > len(t): 8 | return False 9 | matched_s = 0 10 | for char in t: 11 | if matched_s < len(s) and s[matched_s] == char: 12 | matched_s += 1 13 | return matched_s == len(s) 14 | -------------------------------------------------------------------------------- /algorithms/queue.md: -------------------------------------------------------------------------------- 1 | Queue 2 | == 3 | 4 | - Implement a Queue class from scratch with an existing bug, the bug is that it cannot take more than 5 elements. 5 | - Implement a Queue using two stacks. You may only use the standard `push()`, `pop()`, and `peek()` operations traditionally available to stacks. You do not need to implement the stack yourself (i.e. an array can be used to simulate a stack). 6 | -------------------------------------------------------------------------------- /utilities/javascript/matrixTranspose.js: -------------------------------------------------------------------------------- 1 | function matrixTranspose(matrix) { 2 | return matrix[0].map((col, i) => matrix.map(row => row[i])); 3 | } 4 | 5 | const deepEqual = require('./deepEqual'); 6 | 7 | console.log(deepEqual(matrixTranspose([[1]]), [[1]])); 8 | console.log(deepEqual(matrixTranspose([[1, 2]]), [[1], [2]])); 9 | console.log(deepEqual(matrixTranspose([[1, 2], [1, 4]]), [[1, 1], [2, 4]])); 10 | console.log(deepEqual(matrixTranspose([[1, 2, 3], [4, 5, 6]]), [[1, 4], [2, 5], [3, 6]])); 11 | 12 | -------------------------------------------------------------------------------- /algorithms/oop.md: -------------------------------------------------------------------------------- 1 | Object-Oriented Programming 2 | == 3 | 4 | - How would you design a chess game? What classes and objects would you use? What methods would they have? 5 | - How would you design the data structures for a book keeping system for a library? 6 | - Explain how you would design a HTTP server? Give examples of classes, methods, and interfaces. What are the challenges here? 7 | - Discuss algorithms and data structures for a garbage collector? 8 | - How would you implement an HR system to keep track of employee salaries and benefits? 9 | -------------------------------------------------------------------------------- /algorithms/hash-table.md: -------------------------------------------------------------------------------- 1 | Hash Table 2 | == 3 | 4 | - Describe an implementation of a least-used cache, and big-O notation of it. 5 | - A question involving an API's integration with hash map where the buckets of hash map are made up of linked lists. 6 | - Implement data structure `Map` storing pairs of integers (key, value) and define following member functions in O(1) runtime: `void insert(key, value)`, `void delete(key)`, `int get(key)`, `int getRandomKey()`. 7 | - [Source](http://blog.gainlo.co/index.php/2016/08/14/uber-interview-question-map-implementation/). 8 | -------------------------------------------------------------------------------- /front-end/caching.md: -------------------------------------------------------------------------------- 1 | Caching 2 | == 3 | 4 | WIP. 5 | 6 | ## Glossary 7 | 8 | - **Cookies** 9 | 10 | #### References 11 | 12 | - [A Tale of Four Caches](https://calendar.perfplanet.com/2016/a-tale-of-four-caches/) 13 | - [Web Caching Basics: Terminology, HTTP Headers, and Caching Strategies](https://www.digitalocean.com/community/tutorials/web-caching-basics-terminology-http-headers-and-caching-strategies) 14 | - [This browser tweak saved 60% of requests to Facebook](https://code.facebook.com/posts/557147474482256/this-browser-tweak-saved-60-of-requests-to-facebook/) 15 | -------------------------------------------------------------------------------- /algorithms/stack.md: -------------------------------------------------------------------------------- 1 | Stack 2 | == 3 | 4 | - Implementation of an interpreter for a small language that does multiplication/addition/etc. 5 | - Design a `MinStack` data structure that supports a `min()` operation that returns the minimum value in the stack in O(1) time. 6 | - Write an algorithm to determine if all of the delimiters in an expression are matched and closed. 7 | - E.g. `{ac[bb]}`, `[dklf(df(kl))d]{}` and `{[[[]]]}` are matched. But `{3234[fd` and `{df][d}` are not. 8 | - [Source](http://blog.gainlo.co/index.php/2016/09/30/uber-interview-question-delimiter-matching/) 9 | - Sort a stack in ascending order using an additional stack. 10 | -------------------------------------------------------------------------------- /utilities/python/char_prime_map.py: -------------------------------------------------------------------------------- 1 | # For mapping a lowercase character to a prime number. 2 | # Useful for checking whether two strings are anagram or permutations of each other. 3 | primes = { 4 | 'a': 2, 'b': 3, 'c': 5, 'd': 7, 'e': 11, 'f': 13, 5 | 'g': 17, 'h': 19, 'i': 23, 'j': 29, 'k': 31, 'l': 37, 6 | 'm': 41, 'n': 43, 'o': 47, 'p': 53, 'q': 59, 'r': 61, 7 | 's': 67, 't': 71, 'u': 73, 'v': 79, 'w': 83, 'x': 89, 8 | 'y': 97, 'z': 101, ' ': 103, 9 | } 10 | 11 | import functools 12 | 13 | def mul(seq): 14 | return functools.reduce(lambda a, b: a * b, seq, 1) 15 | 16 | def prime_value_of_string(string): 17 | return mul([primes[c] for c in string]) 18 | 19 | print(prime_value_of_string('abcde')) 20 | -------------------------------------------------------------------------------- /utilities/javascript/isSubsequence.js: -------------------------------------------------------------------------------- 1 | function isSubsequence(s, t) { 2 | if (s.length > t.length) { 3 | return false; 4 | } 5 | let matchedLength = 0; 6 | for (let i = 0; i < t.length; i++) { 7 | if (matchedLength < s.length && s[matchedLength] === t[i]) { 8 | matchedLength += 1; 9 | } 10 | } 11 | return matchedLength === s.length; 12 | } 13 | 14 | console.log(isSubsequence('abc', 'abcde') === true); 15 | console.log(isSubsequence('abd', 'abcde') === true); 16 | console.log(isSubsequence('abf', 'abcde') === false); 17 | console.log(isSubsequence('abef', 'abcde') === false); 18 | console.log(isSubsequence('abcdef', 'abcde') === false); 19 | console.log(isSubsequence('a', 'abcde') === true); 20 | -------------------------------------------------------------------------------- /utilities/javascript/binToInt.js: -------------------------------------------------------------------------------- 1 | // Does not handle negative binary numbers. 2 | function binToInt(binary) { 3 | let res = 0; 4 | for (let i = 0; i < binary.length; i++) { 5 | res = res * 2 + (+binary[i]); 6 | } 7 | return res; 8 | } 9 | 10 | console.log(binToInt('0') === parseInt('0', 2) && parseInt('0', 2) === 0); 11 | console.log(binToInt('1') === parseInt('1', 2) && parseInt('1', 2) === 1); 12 | console.log(binToInt('10') === parseInt('10', 2) && parseInt('10', 2) === 2); 13 | console.log(binToInt('11') === parseInt('11', 2) && parseInt('11', 2) === 3); 14 | console.log(binToInt('101') === parseInt('101', 2) && parseInt('101', 2) === 5); 15 | console.log(binToInt('1100011') === parseInt('1100011', 2) && parseInt('1100011', 2) === 99); 16 | -------------------------------------------------------------------------------- /utilities/javascript/matrixClone.js: -------------------------------------------------------------------------------- 1 | function matrixClone(matrix, defaultValue) { 2 | return matrix.map(row => { 3 | return defaultValue === undefined ? row.slice(0) : Array(row.length).fill(defaultValue); 4 | }); 5 | } 6 | 7 | const deepEqual = require('./deepEqual'); 8 | 9 | // Test clone. 10 | const a = [[1, 2], [1, 4]]; 11 | console.log(deepEqual(matrixClone(a), [[1, 2], [1, 4]])); 12 | a[0][0] = 4; 13 | console.log(deepEqual(matrixClone(a), [[1, 2], [1, 4]]) === false); 14 | console.log(deepEqual(matrixClone([[1]]), [[1]])); 15 | 16 | // Test clone with default value. 17 | console.log(deepEqual(matrixClone([[1, 2], [1, 4]], 1), [[1, 1], [1, 1]])); 18 | console.log(deepEqual(matrixClone([[1, 2], [1, 4]], null), [[null, null], [null, null]])); 19 | -------------------------------------------------------------------------------- /algorithms/graph.md: -------------------------------------------------------------------------------- 1 | Graph 2 | == 3 | 4 | - Given a list of sorted words from an alien dictionary, find the order of the alphabet. 5 | - Alien Dictionary Topological Sort question. 6 | - Find if a given string matches any path in a labeled graph. A path may contain cycles. 7 | - Given a bipartite graph, separate the vertices into two sets. 8 | - You are a thief trying to sneak across a rectangular 100 x 100m field. There are alarms placed on the fields and they each have a circular sensing radius which will trigger if anyone steps into it. Each alarm has its own radius. Determine if you can get from one end of the field to the other end. 9 | - Given a graph and two nodes, determine if there exists a path between them. 10 | - Determine if a cycle exists in the graph. 11 | -------------------------------------------------------------------------------- /utilities/javascript/intToBin.js: -------------------------------------------------------------------------------- 1 | // Does not handle negative numbers. 2 | function intToBin(number) { 3 | if (number === 0) { 4 | return '0'; 5 | } 6 | let res = ''; 7 | while (number > 0) { 8 | res = String(number % 2) + res; 9 | number = parseInt(number / 2, 10); 10 | } 11 | return res; 12 | } 13 | 14 | console.log(intToBin(0) === 0..toString(2) && 0..toString(2) === '0'); 15 | console.log(intToBin(1) === 1..toString(2) && 1..toString(2) === '1'); 16 | console.log(intToBin(2) === 2..toString(2) && 2..toString(2) === '10'); 17 | console.log(intToBin(3) === 3..toString(2) && 3..toString(2) === '11'); 18 | console.log(intToBin(5) === 5..toString(2) && 5..toString(2) === '101'); 19 | console.log(intToBin(99) === 99..toString(2) && 99..toString(2) === '1100011'); 20 | -------------------------------------------------------------------------------- /utilities/python/graph_dfs.py: -------------------------------------------------------------------------------- 1 | def graph_dfs(matrix): 2 | rows, cols = len(matrix), len(matrix[0]) 3 | visited = set() 4 | directions = ((0, 1), (0, -1), (1, 0), (-1, 0)) 5 | def dfs(i, j): 6 | if (i, j) in visited: 7 | return 8 | visited.add((i, j)) 9 | # Traverse neighbors. 10 | for direction in directions: 11 | next_i, next_j = i + direction[0], j + direction[1] 12 | if 0 <= next_i < rows and 0 <= next_j < cols: # Check boundary. 13 | # Add any other checking here ^ 14 | dfs(next_i, next_j) 15 | 16 | for i in range(rows): 17 | for j in range(cols): 18 | dfs(i, j) 19 | 20 | graph_dfs([ 21 | [1, 2, 3, 4], 22 | [5, 6, 7, 8], 23 | [9, 10, 11, 12], 24 | ]) 25 | -------------------------------------------------------------------------------- /utilities/javascript/intervalsMerge.js: -------------------------------------------------------------------------------- 1 | // Interval: [start, end]. 2 | // Merges two overlapping intervals into one. 3 | function intervalsMerge(a, b) { 4 | return [Math.min(a[0], b[0]), Math.max(a[1], b[1])]; 5 | } 6 | 7 | const deepEqual = require('./deepEqual'); 8 | 9 | console.log(deepEqual(intervalsMerge([1, 2], [1, 4]), [1, 4])); 10 | console.log(deepEqual(intervalsMerge([1, 2], [0, 4]), [0, 4])); 11 | console.log(deepEqual(intervalsMerge([1, 2], [0, 2]), [0, 2])); 12 | console.log(deepEqual(intervalsMerge([1, 2], [0, 1.5]), [0, 2])); 13 | console.log(deepEqual(intervalsMerge([1, 4], [1, 2]), [1, 4])); 14 | console.log(deepEqual(intervalsMerge([0, 4], [1, 2]), [0, 4])); 15 | console.log(deepEqual(intervalsMerge([0, 2], [1, 2]), [0, 2])); 16 | console.log(deepEqual(intervalsMerge([0, 1.5], [1, 2]), [0, 2])); 17 | -------------------------------------------------------------------------------- /utilities/python/graph_topo_sort.py: -------------------------------------------------------------------------------- 1 | def graph_topo_sort(num_nodes, edges): 2 | from collections import deque 3 | nodes, order, queue = {}, [], deque() 4 | for node_id in range(num_nodes): 5 | nodes[node_id] = { 'in': 0, 'out': set() } 6 | for node_id, pre_id in edges: 7 | nodes[node_id]['in'] += 1 8 | nodes[pre_id]['out'].add(node_id) 9 | for node_id in nodes.keys(): 10 | if nodes[node_id]['in'] == 0: 11 | queue.append(node_id) 12 | while len(queue): 13 | node_id = queue.pop() 14 | for outgoing_id in nodes[node_id]['out']: 15 | nodes[outgoing_id]['in'] -= 1 16 | if nodes[outgoing_id]['in'] == 0: 17 | queue.append(outgoing_id) 18 | order.append(node_id) 19 | return order if len(order) == num_nodes else [] 20 | 21 | print(graph_topo_sort(3, [[0, 1], [0, 2]])) 22 | -------------------------------------------------------------------------------- /utilities/javascript/intervalsIntersect.js: -------------------------------------------------------------------------------- 1 | // Interval: [start, end]. 2 | function intervalsIntersect(a, b) { 3 | return a[0] < b[1] && b[0] < a[1]; 4 | } 5 | 6 | console.log(intervalsIntersect([1, 2], [3, 4]) === false); 7 | console.log(intervalsIntersect([1, 2], [2, 4]) === false); 8 | console.log(intervalsIntersect([1, 2], [1, 4]) === true); 9 | console.log(intervalsIntersect([1, 2], [0, 4]) === true); 10 | console.log(intervalsIntersect([1, 2], [0, 2]) === true); 11 | console.log(intervalsIntersect([1, 2], [0, 1.5]) === true); 12 | console.log(intervalsIntersect([3, 4], [1, 2]) === false); 13 | console.log(intervalsIntersect([2, 4], [1, 2]) === false); 14 | console.log(intervalsIntersect([1, 4], [1, 2]) === true); 15 | console.log(intervalsIntersect([0, 4], [1, 2]) === true); 16 | console.log(intervalsIntersect([0, 2], [1, 2]) === true); 17 | console.log(intervalsIntersect([0, 1.5], [1, 2]) === true); 18 | -------------------------------------------------------------------------------- /utilities/javascript/binarySearch.js: -------------------------------------------------------------------------------- 1 | function binarySearch(arr, target) { 2 | let left = 0; 3 | let right = arr.length - 1; 4 | while (left <= right) { 5 | const mid = left + Math.floor((right - left) / 2); 6 | if (arr[mid] === target) { 7 | return mid; 8 | } 9 | if (arr[mid] < target) { 10 | left = mid + 1; 11 | } else { 12 | right = mid - 1; 13 | } 14 | } 15 | return -1; 16 | } 17 | 18 | console.log(binarySearch([1, 2, 3, 10], 1) === 0); 19 | console.log(binarySearch([1, 2, 3, 10], 2) === 1); 20 | console.log(binarySearch([1, 2, 3, 10], 3) === 2); 21 | console.log(binarySearch([1, 2, 3, 10], 10) === 3); 22 | console.log(binarySearch([1, 2, 3, 10], 9) === -1); 23 | console.log(binarySearch([1, 2, 3, 10], 4) === -1); 24 | console.log(binarySearch([1, 2, 3, 10], 0) === -1); 25 | console.log(binarySearch([1, 2, 3, 10], 11) === -1); 26 | console.log(binarySearch([5, 7, 8, 10], 3) === -1); 27 | -------------------------------------------------------------------------------- /utilities/javascript/matrixTraverse.js: -------------------------------------------------------------------------------- 1 | function traverse(matrix) { 2 | const DIRECTIONS = [[0, 1], [0, -1], [1, 0], [-1, 0]]; 3 | const rows = matrix.length, cols = matrix[0].length; 4 | const visited = matrix.map(row => Array(row.length).fill(false)); 5 | function dfs(i, j) { 6 | if (visited[i][j]) { 7 | return; 8 | } 9 | visited[i][j] = true; 10 | DIRECTIONS.forEach(dir => { 11 | const row = i + dir[0], col = j + dir[1]; 12 | // Boundary check. 13 | if (row < 0 || row >= rows || col < 0 || col >= cols) { 14 | return; 15 | } 16 | // Valid neighbor check. 17 | if (matrix[row][col] !== 1) { 18 | return; 19 | } 20 | dfs(row, col); 21 | }); 22 | } 23 | for (let i = 0; i < rows; i++) { 24 | for (let j = 0; j < cols; j++) { 25 | dfs(i, j); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /algorithms/permutation.md: -------------------------------------------------------------------------------- 1 | Permutation 2 | == 3 | 4 | - You are given a 7 digit phone number, and you should find all possible letter combinations based on the digit-to-letter mapping on numeric pad and return only the ones that have valid match against a given dictionary of words. 5 | - Give all possible letter combinations from a phone number. 6 | - Generate all subsets of a string. 7 | - Print all possible `N` pairs of balanced parentheses. 8 | - E.g. when `N` is `2`, the function should print `(())` and `()()`. 9 | - E.g. when `N` is `3`, we should get `((()))`, `(()())`, `(())()`, `()(())`, `()()()`. 10 | - [Source](http://blog.gainlo.co/index.php/2016/12/23/uber-interview-questions-permutations-parentheses/) 11 | - Given a list of arrays, return a list of arrays, where each array is a combination of one element in each given array. 12 | - E.g. If the input is `[[1, 2, 3], [4], [5, 6]]`, the output should be `[[1, 4, 5], [1, 4, 6], [2, 4, 5], [2, 4, 6], [3, 4, 5], [3, 4, 6]]`. 13 | -------------------------------------------------------------------------------- /front-end/design.md: -------------------------------------------------------------------------------- 1 | Design Questions 2 | == 3 | 4 | ## Autocomplete Widget 5 | 6 | Talk me through a full stack implementation of an autocomplete widget. A user can type text into it, and get back results from a server. 7 | - How would you design a frontend to support the following features: 8 | - Fetch data from a backend API 9 | - Render results as a tree (items can have parents/children - it's not just a flat list) 10 | - Support for checkbox, radio button, icon, and regular list items - items come in many forms 11 | - What does the component's API look like? 12 | - What does the backend API look like? 13 | - What perf considerations are there for complete-as-you-type behavior? Are there any edge cases (for example, if the user types fast and the network is slow)? 14 | - How would you design the network stack and backend in support of fast performance: how do your client/server communicate? How is your data stored on the backend? How do these approaches scale to lots of data and lots of clients? 15 | -------------------------------------------------------------------------------- /algorithms/linked-list.md: -------------------------------------------------------------------------------- 1 | Linked List 2 | == 3 | 4 | - Given a linked list, in addition to the next pointer, each node has a child pointer that can point to a separate list. With the head node, flatten the list to a single-level linked list. 5 | - [Source](http://blog.gainlo.co/index.php/2016/06/12/flatten-a-linked-list/) 6 | - Reverse a singly linked list. Implement it recursively and iteratively. 7 | - Convert a binary tree to a doubly circular linked list. 8 | - Implement an LRU cache with O(1) runtime for all its operations. 9 | - Check distance between values in linked list. 10 | - A question involving an API's integration with hash map where the buckets of hash map are made up of linked lists. 11 | - Given a singly linked list (a list which can only be traversed in one direction), find the item that is located at 'k' items from the end. So if the list is a, b, c, d and k is 2 then the answer is 'c'. The solution should not search the list twice. 12 | - How can you tell if a Linked List is a Palindrome? 13 | -------------------------------------------------------------------------------- /utilities/javascript/graphTopoSort.js: -------------------------------------------------------------------------------- 1 | function graphTopoSort(numberNodes, edges) { 2 | const nodes = new Map(); 3 | const order = []; 4 | const queue = []; 5 | for (let i = 0; i < numberNodes; i++) { 6 | nodes.set(i, { in: 0, out: new Set() }); 7 | } 8 | 9 | edges.forEach(edge => { 10 | const [node_id, pre_id] = edge; 11 | nodes.get(node_id).in += 1; 12 | nodes.get(pre_id).out.add(node_id); 13 | }); 14 | 15 | for (let [node_id, value] of nodes.entries()) { 16 | if (value.in === 0) { 17 | queue.push(node_id); 18 | } 19 | } 20 | 21 | while (queue.length) { 22 | const node_id = queue.shift(); 23 | for (let outgoing_id of nodes.get(node_id).out) { 24 | nodes.get(outgoing_id).in -= 1; 25 | if (nodes.get(outgoing_id).in === 0) { 26 | queue.push(outgoing_id); 27 | } 28 | } 29 | order.push(node_id); 30 | } 31 | 32 | return order.length == numberNodes ? order : []; 33 | } 34 | 35 | console.log(graphTopoSort(3, [[0, 1], [0, 2]])); 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Tay Yang Shun 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /utilities/javascript/deepEqual.js: -------------------------------------------------------------------------------- 1 | function deepEqual(val1, val2) { 2 | if (typeof val1 !== typeof val2) { 3 | return false; 4 | } 5 | 6 | // Array comparison. 7 | if (Array.isArray(val1) && Array.isArray(val2)) { 8 | if (val1.length !== val2.length) { 9 | return false; 10 | } 11 | for (let i = 0; i < val1.length; i++) { 12 | if (!deepEqual(val1[i], val2[i])) { 13 | return false; 14 | } 15 | } 16 | return true; 17 | } 18 | 19 | // Object comparison. 20 | if (typeof val1 === 'object' && typeof val2 === 'object' && val1 !== null) { 21 | const keys1 = Object.keys(val1), keys2 = Object.keys(val2); 22 | if (keys1.length !== keys2.length) { 23 | return false; 24 | } 25 | for (let i = 0; i < keys1.length; i++) { 26 | if (!deepEqual(val1[keys1[i]], val2[keys2[i]])) { 27 | return false; 28 | } 29 | } 30 | return true; 31 | } 32 | 33 | // Primitive comparison. 34 | return val1 === val2; 35 | } 36 | 37 | module.exports = deepEqual; 38 | -------------------------------------------------------------------------------- /algorithms/sorting-searching.md: -------------------------------------------------------------------------------- 1 | Sorting and Searching 2 | == 3 | 4 | - Sorting search results on a page given a certain set of criteria. 5 | - Sort a list of numbers in which each number is at a distance `K` from its actual position. 6 | - Given an array of integers, sort the array so that all odd indexes are greater than the even indexes. 7 | - Given users with locations in a list and a logged-in user with locations, find their travel buddies (people who shared more than half of your locations). 8 | - Search for an element in a sorted and rotated array. 9 | - [Source](http://blog.gainlo.co/index.php/2017/01/12/rotated-array-binary-search/) 10 | - Sort a list where each element is no more than k positions away from its sorted position. 11 | - Search for an item in a sorted, but rotated, array. 12 | - Merge two sorted lists together. 13 | - Give 3 distinct algorithms to find the K largest values in a list of N items. 14 | - Find the minimum element in a sorted rotated array in faster than O(n) time. 15 | - Write a function that takes a number as input and outputs the biggest number with the same set of digits. 16 | - [Source](http://blog.gainlo.co/index.php/2017/01/20/arrange-given-numbers-to-form-the-biggest-number-possible/) 17 | -------------------------------------------------------------------------------- /utilities/python/union_find.py: -------------------------------------------------------------------------------- 1 | ## Union-Find data structure 2 | ## https://en.wikipedia.org/wiki/Disjoint-set_data_structure 3 | 4 | parents = [0, 1, 2, 3, 4, 5, 6] # parent[i] is the parent of i 5 | weights = [1, 1, 1, 1, 1, 1, 1] 6 | 7 | def find_root(parents, p): 8 | '''Average: O(log n)''' 9 | root = p 10 | while parents[root] != root: 11 | root = parents[root] 12 | # Flatten tree 13 | while parents[p] != p: 14 | parents[p], p = root, parents[p] 15 | return root 16 | 17 | def union(parents, p, q): 18 | '''Average: O(log n)''' 19 | p = find_root(parents, p) 20 | q = find_root(parents, q) 21 | # Link the smaller node to the larger node 22 | if weights[p] > weights[q]: 23 | parents[q] = p 24 | weights[p] += weights[q] 25 | else: 26 | parents[p] = q 27 | weights[q] += weights[p] 28 | 29 | 30 | 31 | # Start with all elements separate 32 | # -> [0], [1], [2], [3], [4], [5], [6] 33 | print(find_root(parents, 2) == 2) 34 | 35 | # Merge 1, 2, 3 and 4, 5, 6 36 | # -> [0], [1, 2, 3], [4, 5, 6] 37 | union(parents, 1, 2) 38 | union(parents, 2, 3) 39 | union(parents, 4, 5) 40 | union(parents, 4, 6) 41 | 42 | # Roots of 1, 2, 3 and 4, 5, 6 are the same 43 | print(find_root(parents, 0)) 44 | print(list(find_root(parents, i) for i in (1, 2, 3))) 45 | print(list(find_root(parents, i) for i in (4, 5, 6))) 46 | 47 | # Merge 2, 4 48 | # -> [0], [1, 2, 3, 4, 5, 6] 49 | union(parents, 2, 4) 50 | print(list(find_root(parents, i) for i in (1, 2, 3, 4, 5, 6))) 51 | -------------------------------------------------------------------------------- /front-end/html.md: -------------------------------------------------------------------------------- 1 | HTML 2 | == 3 | 4 | HTML (Hypertext Markup Language) is the structure that all websites are built on. Anyone working on websites and webapps should have a basic understanding of HTML at the very least. A helpful analogy for understanding the importance of HTML is the house scenario. When building a new house, the process can be split into a few key areas; structure (HTML), aesthetics (CSS) and furniture (Content). The HTML is your basic page structure, without the structure, you cannot change how it looks using CSS, or what content is on the page. 5 | 6 | ## Glossary 7 | 8 | - **Doctype** 9 | 10 | ## Deprecated Tags 11 | 12 | There are a number of tags from past versions of HTML that have become deprecated over time. This means that while they are no longer considered valid elements, most browsers should still be able to read and render them. 13 | 14 | ## Script Loading 15 | 16 | - ` 60 | 61 | 62 | -------------------------------------------------------------------------------- /domain/snake-game/snake-game.md: -------------------------------------------------------------------------------- 1 | Snake Game 2 | == 3 | 4 | Design a snake game that is to be played in web browser. 5 | 6 | Client: React + Redux 7 | 8 | Rendering: 9 | Pixel-based graphics. Depending on the intended resolution, can divide the screen into N * M pixels. Can dynamically calculate the size of each pixel. 10 | 11 | Fruit: One pixel. 12 | Snake body: One pixel width made up of connected pixels. 13 | 14 | Model: 15 | { 16 | fruit: { 17 | x, y 18 | }, 19 | snake: { 20 | points: [(x, y), ...] # head is at index 0 21 | direction: north/south/east/west 22 | } 23 | speed: 500, 24 | points: 0 25 | } 26 | 27 | function update() { 28 | next_loc = points[0] + (x, y) # Depends on the direction 29 | if (snake.points.find(next_loc) > 0) { 30 | // die 31 | } 32 | let pts = snake.points; 33 | if (!isEqual(next_loc, fruit)) { 34 | pts = points.removeLast(); 35 | } else { 36 | generate_fruit(); 37 | points++; 38 | } 39 | snake.points = [next_loc, ...pts]; 40 | 41 | // Boundary checking -> die 42 | } 43 | 44 | function generate_fruit() { 45 | // Cannot generate on my own body. 46 | 47 | // First approach: while on body, generate 48 | let next_fruit_location = random_location(); 49 | while (snake.points.find(next_fruit_location) > 0) { 50 | next_fruit_location = random_location(); 51 | } 52 | fruit = next_fruit_location 53 | 54 | // Second approach: brute force 55 | for (let i = 0; i < rows; i++) { 56 | for (let j = 0; j < cols; j++) { 57 | let point = { x: i, y: j } 58 | if (snake.points.find(next_fruit_location) === -1) { 59 | fruit = point 60 | } 61 | } 62 | } 63 | 64 | // Third approach: brute force with random 65 | const available_points = [] 66 | for (let i = 0; i < rows; i++) { 67 | for (let j = 0; j < cols; j++) { 68 | let point = { x: i, y: j } 69 | if (snake.points.find(next_fruit_location) === -1) { 70 | available_points.push(point); 71 | } 72 | } 73 | } 74 | fruit = _.sample(available_points); 75 | } 76 | 77 | setInterval(update, speed); 78 | -------------------------------------------------------------------------------- /utilities/python/rabin_karp_hash.py: -------------------------------------------------------------------------------- 1 | ## Rabin-Karp Rolling Hash 2 | ## Implementation of: https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm#Hash_function_used 3 | ## 4 | ## This rolling hash function is useful when you need to compute the hash of successive substrings 5 | ## of text. E.g. note that going from 'abcd' to 'bcde', we drop the 'a' from the back and add an 'e' 6 | ## on the right. The rolling hash function thus allows us to update the hash in-place O(1) instead of 7 | ## recomputing the full hash of the substring O(m), where m is the length of the substring. 8 | ## 9 | ## NOTE: The implementation below takes in a tuple of integers, to be as general as possible. For use 10 | ## with strings, simply take the ASCII value of each character before passing into the functions. 11 | 12 | BASE = 101 # Arbitrary prime number 13 | 14 | def rk_hash_init(tpl): 15 | '''Initializes the hash with a tuple of integers.''' 16 | return sum(n * BASE ** i for i, n in enumerate(reversed(tpl))) 17 | 18 | def rk_hash_update(curr_hash, size, add_n, rem_n): 19 | '''Updates the hash by removing an integer from the left and appending 20 | an integer to the right. 21 | 22 | curr_hash: The previous hash 23 | size: The size of the rolling window 24 | add_n: The integer appended to the right 25 | rem_n: The integer removed from the left''' 26 | return (curr_hash - (rem_n * BASE ** (size - 1))) * BASE + add_n 27 | 28 | 29 | 30 | abc_hash = rk_hash_init(tuple(map(ord, 'abc'))) # Init the hash with 'abc' 31 | print('abc:', abc_hash) 32 | bcd_hash_1 = rk_hash_update(abc_hash, 3, ord('d'), ord('a')) # Add a 'd' to the right, remove an 'a' from the left 33 | print('bcd 1:', bcd_hash_1) 34 | 35 | zbc_hash = rk_hash_init(tuple(map(ord, 'zbc'))) # Init the hash with 'zbc' 36 | print('zbc:', zbc_hash) 37 | bcd_hash_2 = rk_hash_update(zbc_hash, 3, ord('d'), ord('z')) # Add a 'd' to the right, remove a 'z' from the left 38 | print('bcd 2:', bcd_hash_2) 39 | 40 | # Notice that both hash values are the same despite arriving via different paths 41 | print(bcd_hash_1 == bcd_hash_2) 42 | -------------------------------------------------------------------------------- /interviewers/basics.md: -------------------------------------------------------------------------------- 1 | Basics 2 | == 3 | 4 | ## Disclaimer 5 | 6 | These items will all change based on your specific company and needs but these items area starting point. 7 | 8 | ## Items To Consider 9 | 10 | - **Timeliness** - The interviewee should show up on time, but of course things happen and we must all be understanding that things outside of their control may happen. Try to give a few minutes leeway. 11 | - **Strengths** - Ask the interviewee what they would consider to be their strengths and maybe rate themselves. This gives you a good idea where to start asking technical questions and sets a baseline for expected knowledge of each subject. 12 | - **Keep Things Loose** - This is of course dependent on your industry but try to keep make the interviewee comfortable. Many people get nervous when trying to perform at their best for others and a technical interview is no different. A suggestion is to start with a personal question such as "What are some of your hobbies?" or "What do you like to do for fun?" These types of questions can help relax an interviewee and allows them to perform better. 13 | - **Understand The Position** - Understand that a junior level candidate isn't going to have as much knowledge about languages and frameworks as a senior candidate will. 14 | - **Save Time For Questions** - The interviewee may have questions for you! Give them the ability to ask. Maybe offer up a few questions if they have none, (ie. "What is the typical day here like for my position?", "What is your favorite part about working at __?") 15 | 16 | ## Tech Question Technique 17 | 18 | - **Tools** - Using a text editor such as Sublime or Atom will give the interviewee syntax highlighting but doesn't show compiler errors which can be a help. 19 | - **Nitpicking** - Sometimes psuedocode is okay. If testing in C# do you really need the interviewee to write `Console.WriteLine()` or is `Print()` good enough? 20 | -**Keep Dialog Open** - Don't leave the interviewee alone or sit quietly by as they attempt to coe. Give some subtle hints like "I see you're doing ____, can you think of any other ways to accomplish this?" It's unlikely that the interviewee will be working in a silo should they get the job, is there any reason they should be during the interview? 21 | -------------------------------------------------------------------------------- /non-technical/psychological-tricks.md: -------------------------------------------------------------------------------- 1 | Psychological Tricks 2 | == 3 | 4 | Here are some psychological tricks that will help you ace a job interview. 5 | 6 | - Tailor your answers to the interviewer's age. 7 | - Generation Y interviewers (between 20 and 30): Bring along visual samples of your work and highlight your ability to multitask. 8 | - Generation X interviewers (between 30 and 50): Emphasize your creativity and mention how work/life balance contributes to your success. 9 | - Baby Boomer interviewers (between 50 and 70): Show that you work hard and demonstrate respect for what they've achieved. 10 | - Hold your palms open or steeple your hands. 11 | - Find something in common with your interviewer. 12 | - Mirror the interviewer's body language. 13 | - Compliment the interviewer and the organization without self-promoting. 14 | - Specifically, the students who ingratiated themselves praised the organization and indicated their enthusiasm for working there, and complimented the interviewer. They didn't play up the value of positive events they took credit for or take credit for positive events even if they weren't solely responsible. 15 | - Show confidence and deference simultaneously. 16 | - In a job interview, that means showing deference to your interviewer, while also demonstrating self-confidence. One way to do that is to say something like, "I love your work on [whatever area]. It reminds me of my work on [whatever area]." 17 | - Emphasize how you took control of events in your previous jobs. 18 | - To impress your interviewer, you should talk about past work experiences where you took initiative. 19 | - Be candid about your weaknesses. 20 | - It's wiser to say something genuine like, "I'm not always the best at staying organized," which sounds more honest, and could make your interviewer more inclined to recommend you for the position. 21 | - Speak expressively. 22 | - Showcase your potential. 23 | - You might be tempted to tell your interviewer all about your past accomplishments — but research suggests you should focus more on what you could do in the future, if the organization hires you. 24 | 25 | ###### References 26 | 27 | - [Business Insider](http://www.businessinsider.com/psychological-tricks-to-ace-job-interview-2015-11) 28 | -------------------------------------------------------------------------------- /algorithms/tree.md: -------------------------------------------------------------------------------- 1 | Tree 2 | == 3 | 4 | - Find the height of a tree. 5 | - Find the longest path from the root to leaf in a tree. 6 | - Find the deepest left leaf of a tree. 7 | - Print all paths of a binary tree. 8 | - [Source](http://blog.gainlo.co/index.php/2016/04/15/print-all-paths-of-a-binary-tree/) 9 | - Second largest element of a BST. 10 | - [Source](http://blog.gainlo.co/index.php/2016/06/03/second-largest-element-of-a-binary-search-tree/) 11 | - Given a binary tree and two nodes, how to find the common ancestor of the two nodes? 12 | - [Source](http://blog.gainlo.co/index.php/2016/07/06/lowest-common-ancestor/) 13 | - Find the lowest common ancestor of two nodes in a binary search tree. 14 | - Print the nodes in an n-ary tree level by level, one printed line per level. 15 | - Given a directory of files and folders (and relevant functions), how would you parse through it to find equivalent files? 16 | - Write a basic file system and implement the commands ls, pwd, mkdir, create, rm, cd, cat, mv. 17 | - Compute the intersection of two binary search trees. 18 | - Given a binary tree, output all the node to leaf paths of it. 19 | - Given a string of characters without spaces, is there a way to break the string into valid words without leftover characters? 20 | - Print a binary tree level by level. 21 | - Determine if a binary tree is "complete" (i.e, if all leaf nodes were either at the maximum depth or max depth-1, and were 'pressed' along the left side of the tree). 22 | - Find the longest path in a binary tree. The path may start and end at any node. 23 | - Determine if a binary tree is a BST. 24 | - Given a binary tree, serialize it into a string. Then deserialize it. 25 | - Print a binary tree by column. 26 | - Given a node, find the next element in a BST. 27 | - Find the shortest subtree that consist of all the deepest nodes. The tree is not binary. 28 | - Print out the sum of each row in a binary tree. 29 | - Pretty print a JSON object. 30 | - Convert a binary tree to a doubly circular linked list. 31 | - Find the second largest number in a binary tree. 32 | - Given a tree, find the longest branch. 33 | - Convert a tree to a linked list. 34 | - Given two trees, write code to find out if tree A is a subtree of tree B. 35 | - Deepest node in a tree. 36 | - [Source](http://blog.gainlo.co/index.php/2016/04/26/deepest-node-in-a-tree/) 37 | -------------------------------------------------------------------------------- /utilities/python/heap.py: -------------------------------------------------------------------------------- 1 | # Implements a min-heap. For max-heap, simply reverse all comparison orders. 2 | # 3 | # Note on alternate subroutine namings (used in some textbooks): 4 | # - _bubble_up = siftdown 5 | # - _bubble_down = siftup 6 | 7 | def _bubble_up(heap, i): 8 | while i > 0: 9 | parent_i = (i - 1) // 2 10 | if heap[i] < heap[parent_i]: 11 | heap[i], heap[parent_i] = heap[parent_i], heap[i] 12 | i = parent_i 13 | continue 14 | break 15 | 16 | def _bubble_down(heap, i): 17 | startpos = i 18 | newitem = heap[i] 19 | left_i = 2 * i + 1 20 | while left_i < len(heap): 21 | # Pick the smaller of the L and R children 22 | right_i = left_i + 1 23 | if right_i < len(heap) and not heap[left_i] < heap[right_i]: 24 | child_i = right_i 25 | else: 26 | child_i = left_i 27 | 28 | # Break if heap invariant satisfied 29 | if heap[i] < heap[child_i]: 30 | break 31 | 32 | # Move the smaller child up. 33 | heap[i], heap[child_i] = heap[child_i], heap[i] 34 | i = child_i 35 | left_i = 2 * i + 1 36 | 37 | def heapify(lst): 38 | for i in reversed(range(len(lst) // 2)): 39 | _bubble_down(lst, i) 40 | 41 | def heappush(heap, item): 42 | heap.append(item) 43 | _bubble_up(heap, len(heap) - 1) 44 | 45 | def heappop(heap): 46 | if len(heap) == 1: 47 | return heap.pop() 48 | min_value = heap[0] 49 | heap[0] = heap[-1] 50 | del heap[-1] 51 | _bubble_down(heap, 0) 52 | return min_value 53 | 54 | 55 | 56 | # Example usage 57 | heap = [3, 2, 1, 0] 58 | heapify(heap) 59 | print('Heap(0, 1, 2, 3):', heap) 60 | heappush(heap, 4) 61 | heappush(heap, 7) 62 | heappush(heap, 6) 63 | heappush(heap, 5) 64 | print('Heap(0, 1, 2, 3, 4, 5, 6, 7):', heap) 65 | 66 | sorted_list = [heappop(heap) for _ in range(8)] 67 | print('Heap-sorted list:', sorted_list) 68 | 69 | # Large test case, for randomized tests 70 | import random 71 | 72 | # Heapify 0 ~ 99 73 | heap = list(range(100)) 74 | random.shuffle(heap) 75 | heapify(heap) 76 | 77 | # Push 100 ~ 199 in random order 78 | new_elems = list(range(100, 200)) 79 | random.shuffle(new_elems) 80 | for elem in new_elems: 81 | heappush(heap, elem) 82 | 83 | sorted_list = [heappop(heap) for _ in range(200)] 84 | print(sorted_list == sorted(sorted_list)) 85 | -------------------------------------------------------------------------------- /utilities/python/quick_select.py: -------------------------------------------------------------------------------- 1 | ## QuickSelect -- Linear-time k-th order statistic 2 | ## (i.e. select the k-th smallest element in an unsorted array) 3 | ## https://en.wikipedia.org/wiki/Quickselect 4 | 5 | def partition(array, start, end, pivot): 6 | """Partitions by a pivot value, which might not necessarily be in the array. 7 | This variant is useful when you want to bound your recursion depth by the 8 | range of the input values, and not the length of the array.""" 9 | pivot_index = start 10 | for i in range(start, end): 11 | if array[i] <= pivot: 12 | array[i], array[pivot_index] = array[pivot_index], array[i] 13 | pivot_index += 1 14 | return pivot_index 15 | 16 | import random 17 | def partition_first(array, start, end): 18 | """Selects the first element as pivot. Returns the index where the pivot went to. 19 | In this variant, we can guarantee that the pivot will be in its final sorted position. 20 | We need this guarantee for QuickSelect.""" 21 | if start + 1 == end: 22 | return start 23 | pivot = array[start] 24 | pivot_index = start + 1 25 | for i in range(start + 1, end): 26 | if array[i] <= pivot: 27 | array[i], array[pivot_index] = array[pivot_index], array[i] 28 | pivot_index += 1 29 | # Move pivot to front 30 | array[start], array[pivot_index - 1] = array[pivot_index - 1], array[start] 31 | return pivot_index - 1 32 | 33 | def quick_select(array, k): 34 | """NOTE: k-th smallest element counts from 0!""" 35 | left = 0 36 | right = len(array) 37 | while True: 38 | random_index = random.sample(range(left, right), 1)[0] 39 | array[left], array[random_index] = array[random_index], array[left] 40 | pivot_index = partition_first(array, left, right) 41 | if k == pivot_index: 42 | return array[pivot_index] 43 | if k < pivot_index: 44 | right = pivot_index 45 | else: 46 | left = pivot_index + 1 47 | 48 | 49 | 50 | print(quick_select([0], 0) == 0) 51 | print(quick_select([0, 1, 2, 3, 4], 2) == 2) 52 | print(quick_select([4, 3, 2, 1, 0], 2) == 2) 53 | print(quick_select([1, 3, 4, 2, 0], 2) == 2) 54 | 55 | # Large test case, for randomized tests 56 | lst = list(range(1000)) 57 | for _ in range(10): 58 | k = random.randint(0, 999) 59 | random.shuffle(lst) 60 | print(quick_select(lst, k) == k) 61 | -------------------------------------------------------------------------------- /non-technical/self-introduction.md: -------------------------------------------------------------------------------- 1 | Self Introduction 2 | == 3 | 4 | You can rephrase the question like this: 5 | 6 | "Tell me about your journey into tech. How did you get interested in coding, and why was web development a good fit for you? How is that applicable to our _____ role or company goals?" 7 | 8 | ### The Elevator Pitch 9 | 10 | The Elevator Pitch is an indispensable tool for you as you move forward in your career. An Elevator Pitch is just that -- you pitch yourself to an executive that you want to impress and only have a short elevator ride to do so. Whether you're at a job fair with hundreds of other candidates and you have limited time or you are simply explaining who you are to a potential connection or client, it is important to be able to clearly and accurately describe your knowledge and skillset quickly and succinctly. Here are some tips to develop a good Elevator Pitch: 11 | 12 | - Sell yourself 13 | - The whole point of this is to get you a job or make a connection that benefits your career. 14 | - Tell them who you are, who you work for (or school and major), and what you do. 15 | - KISS (Keep It Simple, Stupid) 16 | - Tell them some highlights from your favorite / most impressive projects. 17 | - Do not delve into the depths of how you reverse engineered a game and decrypted a packet to predict when to use your DKP on a drop. Tell them the executive summary: "I reverse engineered X game by decrypting Y packet to predict Z." If this catches their interest, they *will* ask further questions on their own. 18 | - Why do *they* want *you*? 19 | - This is where you use your knowledge of the company, knowledge of their technology stack(s), your unique talent that they want, etc. in order to solidify your ability to contribute to their company. 20 | - PRACTICE! 21 | - Lastly, you must practice your pitch! Having a great, succinct summary of your skills only helps if you can actually deliver it rapidly! You should practice keeping a quick but easy-to-follow pace that won't overwhelm them but won't bore them. It's a precarious balance, but can be ironed out with practice. 22 | 23 | Having an Elevator Pitch on hand is a great way to create a network and happen upon new job opportunities. There will often be times when you can't prepare for an interview or meeting, and it is incredibly handy to have a practiced pitch. 24 | 25 | ###### References 26 | 27 | - [8 Secrets to Software Engineer Self Introduction](http://blog.gainlo.co/index.php/2016/10/14/8-secretes-software-engineer-self-introduction) 28 | -------------------------------------------------------------------------------- /utilities/python/binary_search.py: -------------------------------------------------------------------------------- 1 | def binary_search(arr, target): 2 | left = 0; 3 | right = len(arr) - 1 4 | while left <= right: 5 | mid = left + (right - left) // 2; 6 | if arr[mid] == target: 7 | return mid 8 | elif arr[mid] < target: 9 | left = mid + 1 10 | else: 11 | right = mid - 1 12 | return -1 13 | 14 | def bisect_left(arr, target): 15 | """Returns the leftmost position that `target` should 16 | go to such that the sequence remains sorted.""" 17 | left = 0 18 | right = len(arr) 19 | while left < right: 20 | mid = (left + right) // 2 21 | if arr[mid] < target: 22 | left = mid + 1 23 | else: 24 | right = mid 25 | return left 26 | 27 | def bisect_right(arr, target): 28 | """Returns the rightmost position that `target` should 29 | go to such that the sequence remains sorted.""" 30 | left = 0 31 | right = len(arr) 32 | while left < right: 33 | mid = (left + right) // 2 34 | if arr[mid] > target: 35 | right = mid 36 | else: 37 | left = mid + 1 38 | return left 39 | 40 | print(binary_search([1, 2, 3, 10], 1) == 0) 41 | print(binary_search([1, 2, 3, 10], 2) == 1) 42 | print(binary_search([1, 2, 3, 10], 3) == 2) 43 | print(binary_search([1, 2, 3, 10], 10) == 3) 44 | print(binary_search([1, 2, 3, 10], 9) == -1) 45 | print(binary_search([1, 2, 3, 10], 4) == -1) 46 | print(binary_search([1, 2, 3, 10], 0) == -1) 47 | print(binary_search([1, 2, 3, 10], 11) == -1) 48 | print(binary_search([5, 7, 8, 10], 3) == -1) 49 | 50 | print(bisect_left([1, 2, 3, 3, 10], 1) == 0) 51 | print(bisect_left([1, 2, 3, 3, 10], 2) == 1) 52 | print(bisect_left([1, 2, 3, 3, 10], 3) == 2) # First "3" is at index 2 53 | print(bisect_left([1, 2, 3, 3, 10], 10) == 4) 54 | 55 | # These return a valid index despite target not being in array. 56 | print(bisect_left([1, 2, 3, 3, 10], 9) == 4) 57 | print(bisect_left([1, 2, 3, 3, 10], 0) == 0) # Insert "0" at front 58 | print(bisect_left([1, 2, 3, 3, 10], 11) == 5) # Insert "5" at back 59 | 60 | print(bisect_right([1, 2, 3, 3, 10], 1) == 1) 61 | print(bisect_right([1, 2, 3, 3, 10], 2) == 2) 62 | print(bisect_right([1, 2, 3, 3, 10], 3) == 4) # Last "3" is at index 3, so insert new "3" at index 4 63 | print(bisect_right([1, 2, 3, 3, 10], 10) == 5) 64 | 65 | # These return a valid index despite target not being in array. 66 | print(bisect_right([1, 2, 3, 3, 10], 9) == 4) 67 | print(bisect_right([1, 2, 3, 3, 10], 0) == 0) # Insert "0" at front 68 | print(bisect_right([1, 2, 3, 3, 10], 11) == 5) # Insert "5" at back 69 | 70 | -------------------------------------------------------------------------------- /utilities/python/trie.py: -------------------------------------------------------------------------------- 1 | class Trie(object): 2 | def __init__(self): 3 | """ 4 | Initialize your data structure here. 5 | """ 6 | self.d = {} 7 | 8 | def insert(self, word): 9 | """ 10 | Inserts a word into the trie. 11 | :type word: str 12 | :rtype: void 13 | """ 14 | curr = self.d 15 | for char in word: 16 | if char not in curr: 17 | curr[char] = {} 18 | curr = curr[char] 19 | curr['#'] = {} # Using an empty dict rather than a boolean value makes recursive traversal easier. 20 | 21 | def search(self, word): 22 | """ 23 | Returns if the word is in the trie. 24 | :type word: str 25 | :rtype: bool 26 | """ 27 | curr = self.d 28 | for char in word: 29 | if char in curr: 30 | curr = curr[char] 31 | else: 32 | return False 33 | return '#' in curr 34 | 35 | def startsWith(self, prefix): 36 | """ 37 | Returns if there is any word in the trie that starts with the given prefix. 38 | :type prefix: str 39 | :rtype: bool 40 | """ 41 | curr = self.d 42 | for char in prefix: 43 | if char in curr: 44 | curr = curr[char] 45 | else: 46 | return False 47 | return True 48 | 49 | def searchRegex(self, word): 50 | """ 51 | Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. 52 | :type word: str 53 | :rtype: bool 54 | """ 55 | def traverse(node, index): 56 | if len(word) == index: 57 | return '#' in node 58 | char = word[index] 59 | if char == '.': 60 | for key in node.keys(): 61 | if traverse(node[key], index+1): 62 | return True 63 | return False 64 | else: 65 | if char not in node: 66 | return False 67 | return traverse(node[char], index + 1) 68 | return traverse(self.d, 0) 69 | 70 | # Example 71 | trie = Trie() 72 | trie.insert('hello') 73 | print(trie.search('hello') == True) 74 | print(trie.startsWith('hello') == True) 75 | print(trie.startsWith('hel') == True) 76 | print(trie.search('world') == False) 77 | print(trie.startsWith('wor') == False) 78 | print(trie.searchRegex('..llo') == True) 79 | print(trie.searchRegex('..llx') == False) 80 | print(trie.searchRegex('..') == False) 81 | -------------------------------------------------------------------------------- /front-end/performance.md: -------------------------------------------------------------------------------- 1 | Performance 2 | == 3 | 4 | WIP. 5 | 6 | ## Glossary 7 | 8 | - **Critical Rendering Path** - 9 | - `requestAnimationFrame` 10 | 11 | ## General Strategies 12 | 13 | 1. Minimize Bytes. 14 | 1. Reduce critical resources. 15 | 1. Reduce CRP length. TODO: Explain what CRP length is. 16 | 17 | ## Loading 18 | 19 | - Minify, Compress, Cache assets. 20 | - Browsers have a [preloader](https://andydavies.me/blog/2013/10/22/how-the-browser-pre-loader-makes-pages-load-faster/) to load assets ahead of time. 21 | 22 | ## Rendering 23 | 24 | - Remove whitespace and comments from HTML/CSS/JS file via minification. 25 | - CSS 26 | - CSS blocks rendering AND JavaScript execution. 27 | - Split up CSS for fewer rendering blocking CSS stylesheets by using media attributes. 28 | - Download only the necessary CSS before the browser can start to render. 29 | - https://developers.google.com/web/fundamentals/design-and-ui/responsive/#css-media-queries 30 | - Use Simpler selectors. 31 | - JavaScript 32 | - JS blocks HTML parsing. If the script is external, it will have to be downloaded first. This incurs latency in network and execution. 33 | - Shift ` 25 | 143 | 144 | 145 | -------------------------------------------------------------------------------- /algorithms/string.md: -------------------------------------------------------------------------------- 1 | String 2 | == 3 | 4 | - Output list of strings representing a page of hostings given a list of CSV strings. 5 | - Given a list of words, find the word pairs that when concatenated form a palindrome. 6 | - Find the most efficient way to identify what character is out of place in a non-palindrome. 7 | - Implement a simple regex parser which, given a string and a pattern, returns a boolean indicating whether the input matches the pattern. By simple, we mean that the regex can only contain the following special characters: `*` (star), `.` (dot), `+` (plus). The star means that there will be zero or more of the previous character in that place in the pattern. The dot means any character for that position. The plus means one or more of previous character in that place in the pattern. 8 | - Find all words from a dictionary that are x edit distance away. 9 | - Given a string IP and number n, print all CIDR addresses that cover that range. 10 | - Write a function called `eval`, which takes a string and returns a boolean. This string is allowed 6 different characters: `0`, `1`, `&`, `|`, `(`, and `)`. `eval` should evaluate the string as a boolean expression, where `0` is `false`, `1` is `true`, `&` is an `and`, and `|` is an `or`. 11 | - E.g `"(0 | (1 | 0)) & (1 & ((1 | 0) & 0))"` 12 | - Given a pattern string like `"abba"` and an input string like `"redbluebluered"`, return `true` if and only if there's a one to one mapping of letters in the pattern to substrings of the input. 13 | - E.g. `"abba"` and `"redbluebluered"` should return `true`. 14 | - E.g. `"aaaa"` and `"asdasdasdasd"` should return `true`. 15 | - E.g. `"aabb"` and `"xyzabcxzyabc"` should return `false`. 16 | - If you received a file in chunks, calculate when you have the full file. Quite an open-ended question. Can assume chunks come with start and end, or size, etc. 17 | - Given a list of names (strings) and the width of a line, design an algorithm to display them using the minimum number of lines. 18 | - Design a spell-checking algorithm. 19 | - Count and say problem. 20 | - Longest substring with `K` unique characters. 21 | - [Source](http://blog.gainlo.co/index.php/2016/04/12/find-the-longest-substring-with-k-unique-characters/) 22 | - Given a set of random strings, write a function that returns a set that groups all the anagrams together. 23 | - [Source](http://blog.gainlo.co/index.php/2016/05/06/group-anagrams/) 24 | - Given a string, find the longest substring without repeating characters. For example, for string `'abccdefgh'`, the longest substring is `'cdefgh'`. 25 | - [Source](http://blog.gainlo.co/index.php/2016/10/07/facebook-interview-longest-substring-without-repeating-characters/) 26 | - Given a string, return the string with duplicate characters removed. 27 | - Write a function that receives a regular expression (allowed chars = from `'a'` to `'z'`, `'*'`, `'.'`) and a string containing lower case english alphabet characters and return `true` or `false` whether the string matches the regex. 28 | - E.g. `'ab*a'`, `'abbbbba'` => `true`. 29 | - E.g. `'ab*b.'`, `'aba'` => `true`. 30 | - E.g. `'abc*'`, `'acccc'` => `false`. 31 | - Given a rectangular grid with letters, search if some word is in the grid. 32 | - Given two strings representing integer numbers (`'123'` , `'30'`) return a string representing the sum of the two numbers: `'153'`. 33 | - A professor wants to see if two students have cheated when writing a paper. Design a function `hasCheated(String s1, String s2, int N)` that evaluates to `true` if two strings have a common substring of length `N`. 34 | - Follow up: Assume you don't have the possibility of using `String.contains()` and `String.substring()`. How would you implement this? 35 | - Print all permutations of a given string. 36 | - Parse a string containing numbers and `'+'`, `'-'` and parentheses. Evaluate the expression. `-2+(3-5)` should return `-4`. 37 | - Output a substring with at most `K` unique characters. 38 | - E.g. `'aabc'` and `k` = 2 => `'aab'`. 39 | - Ensure that there are a minimum of `N` dashes between any two of the same characters of a string. 40 | - E.g. `n = 2, string = 'ab-bcdecca'` => `'ab--bcdec--ca'`. 41 | - Find the longest palindrome in a string. 42 | - Give the count and the number following in the series. 43 | - E.g. `1122344`, next: `21221324`, next: `12112211121214`. 44 | - Count and say problem. 45 | - Compress a string by grouping consecutive similar questions together: 46 | - E.g. `'aaabbbcc' => `'a3b3c2'`. 47 | - You have a string consisting of open and closed parentheses, but parentheses may be imbalanced. Make the parentheses balanced and return the new string. 48 | - Given a set of strings, return the smallest subset that contains prefixes for every string. 49 | - E.g. `['foo', 'foog', 'food', 'asdf']` => `['foo', 'asdf']`. 50 | - Write a function that would return all the possible words generated when using a phone (pre-smartphone era) numpad to type. 51 | - Given a dictionary and a word, find the minimum number of deletions needed on the word in order to make it a valid word. 52 | - [Source](http://blog.gainlo.co/index.php/2016/04/29/minimum-number-of-deletions-of-a-string/) 53 | - How to check if a string contains an anagram of another string? 54 | - [Source](http://blog.gainlo.co/index.php/2016/04/08/if-a-string-contains-an-anagram-of-another-string/) 55 | - Find all k-lettered words from a string. 56 | - Given a string of open and close parentheses, find the minimum number of edits needed to balance a string of parentheses. 57 | - Run length encoding - Write a string compress function that returns `'R2G1B1'` given `'RRGB'`. 58 | - Write a function that finds all the different ways you can split up a word into a concatenation of two other words. 59 | -------------------------------------------------------------------------------- /front-end/css.md: -------------------------------------------------------------------------------- 1 | CSS 2 | == 3 | 4 | CSS (Cascading Style Sheets) are rules to describe how your HTML elements look. Writing good CSS is hard. It usually takes many years of experience and frustration of shooting yourself in the foot before one is able to write maintainable and scalable CSS. CSS, having a global namespace, is fundamentally designed for web documents, and not really for web apps that favor a components architecture. Hence, experienced front end developers have designed methodologies to guide people on how to write organized CSS for complex projects, such as using [SMACSS](https://smacss.com/), [BEM](http://getbem.com/), [SUIT CSS](http://suitcss.github.io/), etc. 5 | 6 | However, the encapsulation of styles that these methodologies bring about are artificially enforced by conventions and guidelines. They break the moment developers do not follow them. 7 | 8 | As you might have realized by now, the front end ecosystem is saturated with tools, and unsurprisingly, tools have been invented to [partially solve some of the problems](https://speakerdeck.com/vjeux/react-css-in-js) with writing CSS at scale. "At scale" means that many developers are working on the same large project and touching the same stylesheets. There is no community-agreed approach on writing [CSS in JS](https://github.com/MicheleBertoli/css-in-js) at the moment, and we are hoping that one day a winner would emerge, just like Redux did, among all the Flux implementations. For now, I would recommend [CSS Modules](https://github.com/css-modules/css-modules). CSS modules is an improvement over existing CSS that aims to fix the problem of global namespace in CSS; it enables you to write styles that are local by default and encapsulated to your component. This feature is achieved via tooling. With CSS modules, large teams can write modular and reusable CSS without fear of conflict or overriding other parts of the app. However, at the end of the day, CSS modules are still being compiled into normal globally-namespaced CSS that browsers recognize, and it is still important to learn and understand how raw CSS works. 9 | 10 | If you are a total beginner to CSS, Codecademy's [HTML & CSS course](https://www.codecademy.com/learn/learn-html-css) will be a good introduction to you. Next, read up on the [Sass preprocessor](http://sass-lang.com/), an extension of the CSS language which adds syntactic improvements and encourages style reusability. Study the CSS methodologies mentioned above, and lastly, CSS modules. 11 | 12 | ## Glossary 13 | 14 | - [**Box Model**](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model) - The CSS box model describes the rectangular boxes that are generated for elements in the document tree and laid out according to the visual formatting model. Each box has a content area (e.g. text, an image, etc.) and optional surrounding padding, border, and margin areas. 15 | - [**Specificity**](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity) - Specificity is how browsers decide which CSS property values are the most relevant to an element and, will therefore be applied. It is a weight that is applied to a given CSS declaration, determined by the number of each selector type in the matching selector. 16 | - When multiple declarations have equal specificity, the last declaration found in the CSS is applied to the element. It only applies when the same element is targeted by multiple declarations. As per CSS rules, directly targeted elements will always take precedence over rules which an element inherits from its ancestor. 17 | - Typically used in type selectors/pseduo elements (`h1`, `div`, `:before`), class/attribute selectors (`.btn`, `[type="radio"]`), pseudo-classes (`:hover`) and ID selectors (`#someElement`). 18 | - Inline styles added to an element always overwrite any styles in external stylesheets, and thus can be thought of as having the highest specificity. 19 | - When an important rule (`!important`) is used on a style declaration, this declaration overrides any other declarations. Try to avoid using `!important`, as it breaks the natural cascading in the stylesheets. Always look for a way to use specificity before even considering `!important`, and only use !important on page-specific CSS that overrides foreign CSS (from external libraries, like Bootstrap). 20 | - [**Positioning**](https://developer.mozilla.org/en-US/docs/Web/CSS/position) - The position CSS property determines how an element will be positioned in a document. The `top`, `right`, `bottom`, and `left` properties would later determine the final location of said positioned element. 21 | - Initial value: `static` 22 | - Values that are frequently used: `relative`, `absolute`, `fixed`, `sticky` 23 | - [**Floats**](https://developer.mozilla.org/en-US/docs/Web/CSS/float) - The `float` CSS property determines where an element should be placed - along the left or right side of its container. This allows text and inline elements to wrap around it. Also note, the element would be removed from the normal *flow* of the web page, though still remaining a part of the flow (in contrast to `position: absolute`). For an element to be `float`, it's value must not be `none`. 24 | - Initial value: `none` 25 | - Values that are frequently used: `left`, `right`, `inline-start`, `inline-end`. 26 | - Additional Notes: Usually, there would be cases that you may want to move an item below any floated elements. E.g, you may want some elements like your paragraphs to remain adjacent to floats, but force headings and footers to be on their own line. See [`clear` attribute](https://developer.mozilla.org/en-US/docs/Web/CSS/clear) for more examples 27 | 28 | ## Writing CSS without Side Effects 29 | 30 | TODO 31 | 32 | ###### References 33 | 34 | - https://philipwalton.com/articles/side-effects-in-css/ 35 | -------------------------------------------------------------------------------- /design/collaborative-editor.md: -------------------------------------------------------------------------------- 1 | Collaborative Document Editor 2 | == 3 | 4 | ## Variants 5 | 6 | - Design Google docs. 7 | - Design a collaborative code editor like Coderpad/Codepile. 8 | - Design a collaborative markdown editor. 9 | 10 | ## Requirements Gathering 11 | 12 | - What is the intended platform? 13 | - Web 14 | - What features are required? 15 | - Creating a document 16 | - Editing a document 17 | - Sharing a document 18 | - Bonus features 19 | - Document revisions and reverting 20 | - Searching 21 | - Commenting 22 | - Chatting 23 | - Executing code (in the case of code editor) 24 | - What is in a document? 25 | - Text 26 | - Images 27 | - Which metrics should we optimize for? 28 | - Loading time 29 | - Synchronization 30 | - Throughput 31 | 32 | ## Core Components 33 | 34 | - Front end 35 | - WebSockets/long polling for real-time communication between front end and back end. 36 | - Back end services behind a reverse proxy. 37 | - Reverse proxy will proxy the requests to the right server. 38 | - Split into a few services for different purposes. 39 | - The benefit of this is that each service can use different languages that best suits its purpose. 40 | - API servers for non-collaborative features and endpoints. 41 | - Ruby/Rails/Django for the server that deals with CRUD operations on data models where performance is not that crucial. 42 | - WebSocket servers for handling document edits and publishing updates to listeners. 43 | - Possibly Node/Golang for WebSocket server which will need high performance as updates are frequent. 44 | - Task queue to persist document updates to the database. 45 | - ELB in front of back end servers. 46 | - MySQL database. 47 | - S3 and CDN for images. 48 | 49 | ## Data Modeling 50 | 51 | - What kind of database to use? 52 | - Data is quite structured. Would go with SQL. 53 | - Design the necessary tables, its columns and its relations. 54 | - `users` 55 | - `id` 56 | - `name` 57 | - `document` 58 | - `id` 59 | - `owner_id` 60 | - `permissions` 61 | - `id` 62 | - `name` 63 | - `document_permissions` 64 | - `id` 65 | - `document_id` 66 | - `user_id` 67 | 68 | ## Collaborative Editing - Client 69 | 70 | - Upon loading of the page and document, the client should connect to the WebSocket server over the WebSocket protocol `ws://`. 71 | - Upon connection, perform a time sync with the server, possibly via Network Time Protocol (NTP). 72 | - The most straightforward way is to send the whole updated document content to the back end, and all users currently viewing the document will receive the updated document. However, there are a few problems with this approach: 73 | - Race condition. If two users editing the document at the same time, the last one to edit will overwrite the changes by the previous user. One workaround is to lock the document when a user is currently editing it, but that will not make it real-time collaborative. 74 | - A large payload (the whole document) is being sent to servers and published to users on each change, and the user is likely to already have most of the content. A lot of redundant data being sent. 75 | - A feasible approach would be to use operational transforms and send just the action deltas to the back end. The back end publishes the action deltas to the listeners. What is considered an action delta? 76 | - (a) Changing a character/word, (b) inserting a character/word/image, (c) deleting a character/word. 77 | - With this approach, the payload will contain only small amount of data, such as (a) type of change, (b) character/word, (c) position in document: line/column, (d) timestamp. Why is the timestamp needed? Read on to find out. 78 | - Updates can also be throttled and batched, to avoid flooding the web server with requests. For example, if a user inserts a 79 | 80 | ## Back End 81 | 82 | The back end is split into a few portions: WebSocket server for receiving and broadcasting document updates, CRUD server for reading and writing non-document-related data, and a task queue for persistence of the document. 83 | 84 | ## WebSocket Server 85 | 86 | - Languages and frameworks that support async requests and non-blocking I/O will be suitable for the collaborative editor server. Node and Golang comes to my mind. 87 | - However, the WebSocket server is not stateless, so is it not that straightforward to scale horizontally. One approach would be for a Load Balancer to use Redis to maintain a map of the client to the WebSocket server instance IP, such that subsequent requests from the same client will be routed to the same server. 88 | - Each document corresponds to a room (more of namespace). Users can subscribe to the events happening within a room. 89 | - When a action delta is being received, blast it out to the listeners within the room and add it to the task queue. 90 | 91 | ## CRUD Server 92 | 93 | - Provides APIs for reading and writing non-document-related data, such as users, permissions. 94 | 95 | ## Task Queue + Worker Service 96 | 97 | - Worker service retrieves messages from the task queue and writes the updated documents to the database in an async fashion. 98 | - Batch the actions together and perform one larger write that consists of multiple actions. For example, instead of persisting to the database once per addition of a word, combine these additions and write them into the database at once. 99 | - Publish the save completion event to the WebSocket server to be published to the listeners, informing that the latest version of the document is being saved. 100 | - Benefit of using a task queue is that as the amount of tasks in the queue goes up, we can scale up the number of worker services to clear the backlog of work faster. 101 | 102 | ## Document Persistence 103 | 104 | TODO 105 | 106 | ###### References 107 | 108 | - http://blog.gainlo.co/index.php/2016/03/22/system-design-interview-question-how-to-design-google-docs/ 109 | -------------------------------------------------------------------------------- /preparing/cheatsheet.md: -------------------------------------------------------------------------------- 1 | Interview Cheatsheet 2 | == 3 | 4 | This is a straight-to-the-point, distilled list of technical interview Do's and Don'ts, mainly for algorithmic interviews. Some of these may apply to only phone screens or whiteboard interviews, but most will apply to both. I revise this list before each of my interviews to remind myself of them and eventually internalized all of them to the point I do not have to rely on it anymore. 5 | 6 | For a detailed walkthrough of interview preparation, refer to the ["Preparing for a Coding Interview"](./) section. 7 | 8 | **Legend:** ✅ = Do, ❌ = Don't, ⚠️ = Situational 9 | 10 | ### 1. Before Interview 11 | 12 | || Things | 13 | |-|-| 14 | |✅|Prepare pen, paper and earphones/headphones.| 15 | |✅|Find a quiet environment with good Internet connection.| 16 | |✅|Ensure webcam and audio are working. There were times I had to restart Chrome to get Hangouts to work again.| 17 | |✅|Request for the option to interview over Hangouts/Skype instead of a phone call; it is easier to send links or text across.| 18 | |✅|Decide on and be familiar with a programming language.| 19 | |✅|Familiarize yourself with the coding environment (CoderPad/CodePen). Set up the coding shortcuts, turn on autocompletion, tab spacing, etc.| 20 | |✅|Prepare answers to the [frequently-asked questions](../non-technical/behavioral.md) in an interview.| 21 | |✅|Prepare some [questions to ask](../non-technical/questions-to-ask.md) at the end of the interview.| 22 | |✅|Dress comfortably. Usually you do not need to wear smart clothes, casual should be fine. T-shirts and jeans are acceptable at most places.| 23 | |✅|Stay calm and composed.| 24 | |⚠️|Turn off the webcam if possible. Most remote interviews will not require video chat and leaving it on only serves as a distraction.| 25 | 26 | ### 2. Introduction 27 | 28 | || Things | 29 | |-|-| 30 | |✅|Introduce yourself in a few sentences under a minute or two.| 31 | |✅|Mention interesting points that are relevant to the role you are applying for.| 32 | |✅|Sound enthusiastic! Speak with a smile and you will naturally sound more engaging.| 33 | |❌|Spend too long introducing yourself. The more time you spend talking the less time you have to code.| 34 | 35 | ### 3. Upon Getting the Question 36 | 37 | || Things | 38 | |-|-| 39 | |✅|Repeat the question back at the interviewer.| 40 | |✅|Clarify any assumptions you made subconsciously. Many questions are under-specified on purpose. A tree-like diagram could very well be a graph that allows for cycles and a naive recursive solution would not work.| 41 | |✅|Clarify input format and range. Ask whether input can be assumed to be well-formed and non-null.| 42 | |✅|Work through a small example to ensure you understood the question.| 43 | |✅|Explain a high level approach even if it is a brute force one.| 44 | |✅|Improve upon the approach and optimize. Reduce duplicated work and cache repeated computations.| 45 | |✅|Think carefully, then state and explain the time and space complexity of your approaches.| 46 | |✅|If stuck, think about related problems you have seen before and how they were solved. Check out the [tips](../algorithms) in this section.| 47 | |❌|Ignore information given to you. Every piece is important.| 48 | |❌|Jump into coding straightaway.| 49 | |❌|Start coding without interviewer's green light.| 50 | |❌|Appear too unsure about your approach or analysis.| 51 | 52 | ### 4. During Coding 53 | 54 | || Things | 55 | |-|-| 56 | |✅|Explain what you are coding/typing to the interviewer, what you are trying to achieve.| 57 | |✅|Practice good coding style. Clear variable names, consistent operator spacing, proper indentation, etc.| 58 | |✅|Type/write at a reasonable speed.| 59 | |✅|As much as possible, write actual compilable code, not pseudocode.| 60 | |✅|Write in a modular fashion. Extract out chunks of repeated code into functions.| 61 | |✅|Ask for permission to use trivial functions without having to implement them; saves you some time.| 62 | |✅|Use the hints given by the interviewer.| 63 | |✅|Demonstrate mastery of your chosen programming language.| 64 | |✅|Demonstrate technical knowledge in data structures and algorithms.| 65 | |✅|If you are cutting corners in your code, state that out loud to your interviewer and say what you would do in a non-interview setting (no time constraints). E.g., I would write a regex to parse this string rather than using `split()` which may not cover all cases.| 66 | |✅|Practice whiteboard space-management skills.| 67 | |⚠️|Reasonable defensive coding. Check for nulls, empty collections, etc. Can omit if input validity has been clarified with the interviewer.| 68 | |❌|Remain quiet the whole time.| 69 | |❌|Spend too much time writing comments.| 70 | |❌|Use extremely verbose variable names.| 71 | |❌|Copy and paste code without checking.| 72 | |❌|Interrupt your interviewer when they are talking. Usually if they speak, they are trying to give you hints or steer you in the right direction.| 73 | |❌|Write too big (takes up too much space) or too small (illegible) if on a whiteboard.| 74 | 75 | ### 5. After Coding 76 | 77 | || Things | 78 | |-|-| 79 | |✅|Scan through your code for mistakes as if it was your first time seeing code written by someone else.| 80 | |✅|Check for off-by-one errors.| 81 | |✅|Come up with more test cases. Try extreme test cases.| 82 | |✅|Step through your code with those test cases.| 83 | |✅|Look out for places where you can refactor.| 84 | |✅|Reiterate the time and space complexity of your code.| 85 | |✅|Explain trade-offs and how the code/approach can be improved if given more time.| 86 | |❌|Immediately announce that you are done coding. Do the above first!| 87 | |❌|Argue with the interviewer. They may be wrong but that is very unlikely given that they are familiar with the question.| 88 | 89 | ### 6. Wrap Up 90 | 91 | || Things | 92 | |-|-| 93 | |✅|Ask questions. More importantly, ask good and engaging questions that are tailored to the company! Pick some questions from [this list](../non-technical/questions-to-ask.md).| 94 | |✅|Thank the interviewer.| 95 | |⚠️|Ask about your interview performance. It can get awkward.| 96 | |❌|End the interview without asking any questions.| 97 | 98 | ### 7. Post Interview 99 | 100 | || Things | 101 | |-|-| 102 | |✅|Record the interview questions and answers down as these can be useful for future reference.| 103 | |⚠️|Send a follow up email to your interviewer(s) thanking them for their time and the opportunity to interview with them.| 104 | -------------------------------------------------------------------------------- /domain/tic-tac-toe/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 24 | 25 | 26 |

Tic Tac Toe

27 |

Current player turn:

28 |
29 | 30 | 177 | 178 | 179 | -------------------------------------------------------------------------------- /front-end/javascript.md: -------------------------------------------------------------------------------- 1 | JavaScript 2 | == 3 | 4 | WIP. 5 | 6 | ## Contents 7 | 8 | - [Glossary](#glossary) 9 | - [Core Language](#core-language) 10 | - [Design Patterns](#design-patterns) 11 | - [Strict Mode](#strict-mode) 12 | 13 | ## Glossary 14 | 15 | - **Closure** - "Closure is when a function is able to remember and access its lexical scope even when that function is executing outside its lexical scope." - [YDKJS](https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch5.md) 16 | - **Event Loop** - The event loop is a single-threaded loop that monitors the call stack and checks if there is any work to be done in the message queue. If the call stack is empty and there are callback functions in the message queue, a message is dequeued and pushed onto the call stack to be executed. 17 | - **Hoisting** - "Wherever a var appears inside a scope, that declaration is taken to belong to the entire scope and accessible everywhere throughout." - [YDKJS](https://github.com/getify/You-Dont-Know-JS/blob/master/up%20%26%20going/ch2.md#hoisting) 18 | - **Promise** - "The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value." - [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) 19 | - Promises can contain an immediate value. 20 | - **Prototype** - TBD 21 | - **This** - The `this` keyword does not refer to the function in which `this` is used or that function's scope. Javascript uses [4 rules](https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch2.md#determining-this) to determine if `this` will reference an arbitrary object, *undefined* or the *global* object inside a particular function call. 22 | 23 | ## Core Language 24 | 25 | ### Variables 26 | 27 | - Reference: [Types and Grammar](https://github.com/getify/You-Dont-Know-JS/blob/master/types%20%26%20grammar/ch1.md) 28 | - Types 29 | - Scopes 30 | - [Coercion](https://github.com/getify/You-Dont-Know-JS/blob/master/up%20%26%20going/ch2.md#coercion) 31 | 32 | ### Functions 33 | 34 | - Reference: [this & Object Prototypes](https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch3.md) 35 | - Declaration vs Expression 36 | - Closures 37 | - `.call`, `.apply` and `.bind` 38 | - Currying 39 | - Arrow functions and lexical this 40 | 41 | ### Prototypes and Objects 42 | 43 | - Reference: [this & Object Prototypes](https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20&%20closures/README.md#you-dont-know-js-scope--closures) 44 | - Prototype chain 45 | - `this` keyword 46 | - https://rainsoft.io/gentle-explanation-of-this-in-javascript/ 47 | - https://codeburst.io/the-simple-rules-to-this-in-javascript-35d97f31bde3 48 | - Classes 49 | - Methods 50 | - Use non-arrow functions for methods that will be called using the `object.method()` syntax because you need the value of `this` to point to the instance itself. 51 | 52 | ### Async 53 | 54 | - Reference: [Async and Peformance](https://github.com/getify/You-Dont-Know-JS/blob/master/async%20&%20performance/README.md#you-dont-know-js-async--performance) 55 | - `setTimeout`, `setInterval` and event loop 56 | - [setImmediate() vs nextTick() vs setTimeout(fn,0)](http://voidcanvas.com/setimmediate-vs-nexttick-vs-settimeout/) 57 | - Event Loop 58 | - Debounce and Throttle 59 | - Throttling enforces a maximum number of times a function can be called over time. 60 | - Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. 61 | - https://css-tricks.com/debouncing-throttling-explained-examples/ 62 | - Callbacks 63 | - [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) 64 | - [Async](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) and [Await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) in ES7 65 | 66 | **Reference** 67 | 68 | - https://www.vikingcodeschool.com/falling-in-love-with-javascript/the-javascript-event-loop 69 | 70 | ## Design Patterns 71 | 72 | - https://addyosmani.com/resources/essentialjsdesignpatterns/book/ 73 | 74 | ## Strict Mode 75 | 76 | 1. Strict mode eliminates some JavaScript silent errors by changing them to throw errors. 77 | 1. Strict mode fixes mistakes that make it difficult for JavaScript engines to perform optimizations. Strict mode code can sometimes be made to run faster than identical code that's not strict mode. 78 | 1. Strict mode prohibits some syntax likely to be defined in future versions of ECMAScript. 79 | 80 | **Converting Mistakes into Errors** 81 | 82 | - Prevent accidental creation of global variables. 83 | - Makes assignments which would otherwise silently fail throw an exception. 84 | - Makes attempts to delete undeletable properties throw errors. 85 | - Requires that all properties named in an object literal be unique. Duplicate property names are a syntax error in strict mode. 86 | - Requires that function parameter names be unique. In normal code the last duplicated argument hides previous identically-named arguments. 87 | - Forbids setting properties on primitive values in ES6. Without strict mode, setting properties is simply ignored (no-op), with strict mode, however, a `TypeError` is thrown. 88 | 89 | **Simplifying Variable Uses** 90 | 91 | - Prohibits `with`. 92 | - `eval` of strict mode code does not introduce new variables into the surrounding scope. 93 | - Forbids deleting plain variables. `delete` name in strict mode is a syntax error: `var x; delete x; // !!! syntax error`. 94 | 95 | **Paving the way for future ECMAScript versions** 96 | 97 | - Future ECMAScript versions will likely introduce new syntax, and strict mode in ECMAScript 5 applies some restrictions to ease the transition. It will be easier to make some changes if the foundations of those changes are prohibited in strict mode. 98 | - First, in strict mode a short list of identifiers become reserved keywords. These words are `implements`, `interface`, `let`, `package`, `private`, `protected`, `public`, `static`, and `yield`. In strict mode, then, you can't name or use variables or arguments with these names. 99 | - Second, strict mode prohibits function statements not at the top level of a script or function. 100 | 101 | ## Transpilation: TBD 102 | 103 | ## Useful Links 104 | 105 | - https://medium.com/javascript-scene/10-interview-questions-every-javascript-developer-should-know-6fa6bdf5ad95#.l2n8icwl4 106 | - https://github.com/mbeaudru/modern-js-cheatsheet 107 | - [Functional Programming in Javascript - Javascript Allonge](https://leanpub.com/javascriptallongesix/read) 108 | - [Dr. Frisby's Mostly Adequate Guide to Functional Programming](https://drboolean.gitbooks.io/mostly-adequate-guide/content/) 109 | -------------------------------------------------------------------------------- /non-technical/questions-to-ask.md: -------------------------------------------------------------------------------- 1 | Questions to Ask 2 | == 3 | 4 | Here are some good questions to ask at the end of the interview, extracted from various sources. The ones in **bold** are the ones that tend to make the interviewer go "That's a good question" and pause and think for a bit. 5 | 6 | ### General 7 | 8 | - **What are you most proud about in your career so far?** 9 | - **What is the most important/valuable thing you have learnt from working here?** 10 | - How do your clients and customers define success? 11 | - What would you change around here if you could? 12 | - What are some weaknesses of the organization? 13 | - What does a typical day look like for you? 14 | - What do you think the company can improve at? 15 | - How would you see yourself growing at this company in the next few years? 16 | - Was there a time where you messed up and how was it handled? 17 | - Why did you choose to come to this company? 18 | - When you were last interviewing, what were some of your other options, and what made you choose this company? 19 | - What was something you wish someone would have told you before you joined? 20 | - What was your best moment so far at the company? 21 | 22 | ### Culture 23 | 24 | - **What is the most frustrating part about working here?** 25 | - **What is unique about working at this company that you have not experienced elsewhere?** 26 | - **What is something you wish were different about your job?** 27 | - How will the work I will be doing contribute to the organization's mission? 28 | - What do you like about working here? 29 | - What is your policy on working from home/remotely? 30 | - (If the company is a startup) When was the last time you interacted with a founder? What was it regarding? Generally how involved are the founders in the day-to-day? 31 | - Does the company culture encourage entrepreneurship? Could you give me any specific examples? 32 | 33 | ### Technical 34 | 35 | These questions are suitable for any technical role. 36 | 37 | - **What are the engineering challenges that the company/team is facing?** 38 | - **What has been the worst technical blunder that has happened in the recent past? How did you guys deal with it? What changes were implemented afterwards to make sure it didn't happen again?** 39 | - **What is the most costly technical decision made early on that the company is living with now?** 40 | - **What is the most fulfilling/exciting/technically complex project that you've worked on here so far?** 41 | - How do you evaluate new technologies? Who makes the final decisions? 42 | - How do you know what to work on each day? 43 | - How would you describe your engineering culture? 44 | - How has your role changed since joining the company? 45 | - What is your stack? What is the rationale for/story behind this specific stack? 46 | - Do you tend to roll your own solutions more often or rely on third party tools? What's the rationale in a specific case? 47 | - How does the engineering team balance resources between feature requests and engineering maintenance? 48 | - What do you measure? What are your most important product metrics? 49 | - What does the company do to nurture and train its employees? 50 | - How often have you moved teams? What made you join the team you're on right now? If you wanted to move teams, what would need to happen? 51 | - If you hire person, what do you have for him to study product you're working on and processes in general? Do you have specifications, requirements, documentation? 52 | - There's "C++" (or Python, Swift or any other tech) in the job description. How will you estimate my proficiency in this tech in 3 months? 53 | 54 | ### Product 55 | 56 | - Tell me about the main products of your company. 57 | - What is the current version of product? (If it is v1.0 or similar - there could be a lot of chaos to work with) 58 | - What products are your main competitors? 59 | - What makes your product competitive? 60 | - When are you planning to provide the next release? (If in several months, it would mean a lot of requirements specified in job description are not needed right now) 61 | 62 | ### Management 63 | 64 | These questions are suitable for asking Engineering Managers, especially useful for the Team Matching phase of Google interviews or post-offer calls that your recruiters set up with the various team managers. 65 | 66 | - **How do you train/ramp up engineers who are new to the team?** 67 | - **What does success look like for your team?** 68 | - **What qualities do you look out for when hiring for this role?** 69 | - **What are the strengths and weaknesses of the current team? What is being done to improve upon the weaknesses?** 70 | - **Can you tell me about a time you resolved an interpersonal conflict?** 71 | - How did you become a manager? 72 | - How do your engineers know what to work on each day? 73 | - What is your team's biggest challenge right now? 74 | - How do you measure individual performance? 75 | - How often are 1:1s conducted? 76 | - What is the current team composition like? 77 | - What opportunities are available to switch roles? How does this work? 78 | 79 | ### Leadership 80 | 81 | These questions are intended for senior level management, such as CEO, CTO, VPs. Candidates who interview with startups usually get to speak with senior level management. 82 | 83 | - How are you funded? 84 | - Are you profitable? If no, what's your plan for becoming profitable? 85 | - What assurance do you have that this company will be successful? 86 | - Tell me about your reporting structure. 87 | - How does the company decide on what to work on next? 88 | 89 | ### HR 90 | 91 | - **How do you see this position evolving in the next three years?** 92 | - **Who is your ideal candidate and how can I make myself more like them?** 93 | - What concerns/reservations do you have about me for this position? 94 | - What can I help to clarify that would make hiring me an easy decision? 95 | - How does the management team deal with mistakes? 96 | - If you could hire anyone to join your team, who would that be and why? 97 | - How long does the average engineer stay at the company? 98 | - Why have the last few people left? 99 | - Have you ever thought about leaving? If you were to leave, where would you go? 100 | 101 | ###### References 102 | 103 | - [Business Insider](http://www.businessinsider.sg/impressive-job-interview-questions-2015-3/) 104 | - [Lifehacker](http://lifehacker.com/ask-this-question-to-end-your-job-interview-on-a-good-n-1787624433) 105 | - [Fastcompany](https://www.fastcompany.com/40406730/7-questions-recruiters-at-amazon-spotify-and-more-want-you-to-ask) 106 | - [Questions I'm asking in interviews](http://jvns.ca/blog/2013/12/30/questions-im-asking-in-interviews/) 107 | - [How to interview your interviewers](http://blog.alinelerner.com/how-to-interview-your-interviewers/) 108 | - [How to Break Into the Tech Industry—a Guide to Job Hunting and Tech Interviews](https://haseebq.com/how-to-break-into-tech-job-hunting-and-interviews/) 109 | - [A developer's guide to interviewing](https://medium.freecodecamp.org/how-to-interview-as-a-developer-candidate-b666734f12dd) 110 | - [Questions I'm asking in interviews 2017](https://cternus.net/blog/2017/10/10/questions-i-m-asking-in-interviews-2017/) 111 | -------------------------------------------------------------------------------- /non-technical/interview-formats.md: -------------------------------------------------------------------------------- 1 | Interview Formats 2 | == 3 | 4 | The following interview formats are based on my experience interviewing with Bay Area companies. Formats would differ slightly depending on the roles you are applying to. Many companies like to use [CoderPad](https://coderpad.io/) for collaborative code editing. CoderPad supports running of the program, so you might be asked to fix your code such that it can be run. For front end interviews, many companies like to use [CodePen](https://codepen.io/), and it will be worth your time to familiarize yourself with the user interfaces of such web-based coding environments. 5 | 6 | For on-site interviews at smaller (non-public) companies, most will allow (and prefer) that you use your own laptop. Hence it is important that you prepare your development environment in advance. 7 | 8 | ## Companies 9 | 10 | - [Airbnb](#airbnb) 11 | - [Asana](#asana) 12 | - [Dropbox](#dropbox) 13 | - [Facebook](#facebook) 14 | - [Google](#google) 15 | - [Lyft](#lyft) 16 | - [Palantir](#palantir) 17 | - [WhatsApp](#whatsapp) 18 | 19 | ### Airbnb 20 | 21 | - Recruiter phone screen. 22 | - Technical phone interview: 23 | - 1 or 2 x Algorithm/front end on CoderPad/CodePen. 24 | - On-site (General): 25 | - 2 x Algorithm coding on CoderPad. 26 | - 1 x System design/architecture. 27 | - 1 x Past experience/project. 28 | - 2 x Cross functional. 29 | - On-site (Front End): 30 | - 2 x Front end coding on CodePen. Use any framework/library. 31 | - 1 x General coding on your own laptop. 32 | - 1 x Past experience/project. 33 | - 2 x Cross functional. 34 | - Tips: 35 | - All sessions involve coding on your own laptop. Prepare your development environment in advance. 36 | - You are allowed to look up APIs if you need to. 37 | - They seem to place high emphasis on compilable, runnable code in all their coding rounds. 38 | - Cross functional interviews will involve getting Airbnb employees from any discipline to speak with you. These interviews are mostly non-technical but are extremely important to Airbnb because they place a high emphasis on cultural fit. Do look up the Airbnb section of the behavioural questions to know what sort of questions to expect. 39 | 40 | ### Asana 41 | 42 | - Recruiter phone screen. 43 | - Technical phone interview. 44 | - On-site (Product Engineer): 45 | - 3 x Algorithm and system design on whiteboard within the same session. 46 | - 1 x Algorithm on laptop and system design. This session involves writing code on your own laptop to solve 3 well-defined algorithm problems in around 45 minutes after which an engineer will come in and review the code with you. You are not supposed to run the code while working on the problem. 47 | - Tips: 48 | - No front end questions were asked. 49 | - Asana places high emphasis on System Design and makes heavy use of the whiteboard. You do not necessarily have to write code for the algorithm question of the first three interviews. 50 | - All 4 sessions involve algorithms and system design. One of the sessions will be conducted by an Engineering Manager. 51 | - The last session will involve coding on your own laptop. Prepare your development environment in advance. 52 | - Regardless of Product Engineer or Engineering Generalist position, their interview format and questions are similar. 53 | 54 | ### Dropbox 55 | 56 | - Recruiter phone screen. 57 | - Technical phone interviews: 58 | - 2 x Algorithm/front end on CoderPad/CodePen. 59 | - On-site (Front End): 60 | - 2 x Front end on CodePen. Only Vanilla JS or jQuery allowed. 61 | - 1 x General coding on CoderPad. 62 | - 1 x All around. Meet with an Engineering Manager and discussing past experiences and working style. 63 | - Tips: 64 | - You can code on your own laptop and look up APIs. 65 | - Dropbox recruiters are very nice and will give you helpful information on what kind of questions to expect for the upcoming sessions. 66 | - One of the front end sessions involve coding up a pixel-perfect version of a real page on www.dropbox.com. You'll be given a spec of the desired page and you'll be asked to create a working version during the interview. 67 | 68 | ### Facebook 69 | 70 | - Recruiter phone screen. 71 | - Technical phone interviews: 72 | - 1 or 2 x Algorithm/front end on Skype/CoderPad. 73 | - On-site (Front End): 74 | - 2 x Technical coding interview on whiteboard (Ninja). 75 | - 1 x Behavioural (Jedi). Meet with an Engineering Manager and discussing past experiences and working style. 76 | - 1 x Design/architecture on whiteboard (Pirate). 77 | - Tips: 78 | - You are only allowed to use the whiteboard (or wall). No laptops involved. 79 | - For the Jedi round, you may be asked a technical question at the end of it. Front end candidates will be given a small HTML/CSS problem nearing the end of the session. 80 | - For the Ninja rounds, you may be asked one to two questions depending on how fast you progress through the question. 81 | 82 | ### Google 83 | 84 | - Recruiter phone screen. 85 | - Technical phone interview: 86 | - 1 or 2 x algorithm on Google Doc. 87 | - On-site (Front End): 88 | - 3 x Front end on whiteboard. Have to use Vanilla JS (or at the most, jQuery). 89 | - 2 x Algorithm on whiteboard. 90 | - Team matching. 91 | - Speak with managers from different teams who are interested in your profile. 92 | - Tips: 93 | - You are only allowed to use the whiteboard. No laptops involved. 94 | - In rare cases, candidates may even be allowed to skip the phone interview round and advanced to on-site directly. 95 | - For non-fresh grads, you only receive an offer if you are successfully matched with a team. 96 | 97 | ### Lyft 98 | 99 | - Recruiter phone screen. 100 | - Technical phone interview: 101 | - 1 x Algorithm/Front end over JSFiddle. 102 | - On-site (Front End): 103 | - 4 x Front end on Coderpad/your own laptop. Use any language/framework. 104 | - 1 x Behavioural. Meet with an Engineering Manager and go through candidate's resume. 105 | - Tips: 106 | - Can use whiteboard and/or laptop. 107 | - For front end coding, I opted to use React and had to set up the projects on the spot using `create-react-app`. 108 | 109 | ### Palantir 110 | 111 | - Recruiter phone screen. 112 | - Technical phone interview: 113 | - 1 x Algorithm over HackerRank CodePair and Skype. 114 | - On-site (General): 115 | - 2 x Algorithm on whiteboard. 116 | - 1 x Decomposition (system design) on whiteboard. 117 | - On-site (Front End): 118 | - 1 x Front end on your own laptop. This session lasts about 1.5 hours. Use any library/framework. 119 | - 1 x Decomposition (system design) on whiteboard. 120 | - Tips: 121 | - I opted to use React and had to set up projects on the spot using `create-react-app`. 122 | - You may be asked to meet with Engineering Managers after the technical sessions and it's not necessarily a good/bad thing. 123 | 124 | ### WhatsApp 125 | 126 | - Recruiter phone screen. 127 | - Technical phone interview: 128 | - 2 x Algorithm over CoderPad. 129 | - On-site (Web Client Developer): 130 | - 4 x Algorithm on whiteboard. 131 | - Tips: 132 | - No front end questions were asked. 133 | - 1 of the interviewers is an Engineering Manager. 134 | -------------------------------------------------------------------------------- /front-end/dom.md: -------------------------------------------------------------------------------- 1 | DOM 2 | == 3 | 4 | ## Glossary 5 | 6 | - **Event Delegation** - Event delegation refers to the process of using event propagation (bubbling) to handle events at a higher level in the DOM than the element on which the event originated. It allows us to attach a single event listener for elements that exist now or in the future. 7 | 8 | ## Node API 9 | 10 | Here's a list of the essential and more common DOM `Node` APIs. It is important to know how to traverse and manipulate the DOM in vanilla JS without jQuery. 11 | 12 | **Properties** 13 | 14 | - `Node.childNodes` - Returns a live `NodeList` containing all the children of this node. `NodeList` being live means that if the children of the Node change, the `NodeList` object is automatically updated. 15 | - `Node.firstChild` 16 | - `Node.lastChild` 17 | - `Node.nextSibling` - Returns a `Node` representing the next node in the tree, or `null` if there isn't such a node. 18 | - `Node.nodeName` - `DIV`, `SPAN`, etc. Note that it is in upper case in HTML documents, and has the same value as `Element.tagName`. 19 | - `Node.parentNode` - Returns a `Node` that is the parent of this node. If there is no such node, like if this node is the top of the tree or if it doesn't participate in a tree, this property returns `null`. 20 | - `Node.parentElement` - Returns an `Element` that is the parent of this node. If the node has no parent, or if that parent is not an `Element`, this property returns `null`. 21 | - `Node.previousSibling` - Returns a `Node` representing the previous node in the tree, or `null` if there isn't such a node. 22 | - `Node.textContent` - Returns / Sets the textual content of an element and all its descendants. 23 | 24 | **Methods** 25 | 26 | - `Node.appendChild(node)` - Adds the specified `node` argument as the last child to the current node. If the argument referenced an existing node on the DOM tree, the node will be detached from its current position and attached at the new position. 27 | - `Node.cloneNode(node)` - Clone a `Node`, and optionally, all of its contents. By default, it clones the content of the node. 28 | - `Node.contains(node)` - Returns a `Boolean` value indicating whether a node is a descendant of a given node or not. 29 | - `Node.hasChildNodes()` - Returns a `Boolean` indicating if the element has any child nodes, or not. 30 | - `Node.insertBefore(newNode, referenceNode)` - Inserts the first `Node` before the reference node as a child of the current node. If `referenceNode` is `null`, the `newNode` is inserted at the end of the list of child nodes. 31 | - `Node.removeChild(node)` - Removes a child node from the current element, which must be a child of the current node. 32 | - `Node.replaceChild(newChild, oldChild)` - Replaces one child node of the specified node with another node. 33 | 34 | ## Element API 35 | 36 | Here's a list of the essential and more common DOM `Element` APIs. It is important to know how to traverse and manipulate the DOM in vanilla JS without jQuery. 37 | 38 | **Properties** 39 | 40 | - `Element.attributes` - Returns a `NamedNodeMap` object containing the assigned attributes of the corresponding HTML element. 41 | - `Element.classList` - Returns a `DOMTokenList` containing the list of class attributes. 42 | - `DOMTokenList.add(String [, String])` - Add specified class values. If these classes already exist in attribute of the element, they are ignored. 43 | - `DOMTokenList.remove(String [, String])` - Remove specified class values. 44 | - `DOMTokenList.toggle(String [, force])` - Toggle specified class value. If second argument is present and evaluates to `true`, add the class value, else remove it. 45 | - `DOMTokenList.contains(String)` - Checks if specified class value exists in class attribute of the element. 46 | - `Element.className` - A `DOMString` representing the class of the element. 47 | - `Element.id` 48 | - `Element.innerHTML` - Returns a `DOMString` representing the markup of the element's content or parse the content string and assigns the resulting nodes as children of the element. 49 | - `Element.tagName` - `DIV`, `SPAN`, etc. Note that it is in upper case in HTML documents, and has the same value as `Node.nodeName`. 50 | 51 | **Methods** 52 | 53 | - `EventTarget.addEventListener(type, callback, options)` - Registers an event handler to a specific event type on the element. Read up more on the `options` [here](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener). 54 | - `EventTarget.removeEventListener(type, callback, options)` - Removes an event listener from the element. Read up more on the `options` [here](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener). 55 | - `Element.closest(selectors)` - Returns the closest ancestor of the current element (or the current element itself) which matches the selectors given in parameter. If there isn't such an ancestor, it returns `null`. 56 | - `Element.getElementsByClassName(classNames)`- Returns a live `HTMLCollection` that contains all descendants of the current element that possess the list of classes given in the parameter. 57 | - `Element.getElementsByTagName(tagName)` - Returns a live `HTMLCollection` containing all descendant elements, of a particular tag name, from the current element. 58 | - `Element.querySelector(selectors)` - Returns the first `Node` which matches the specified selector string relative to the element. 59 | - `Element.querySelectorAll(selectors)` - Returns a `NodeList` of nodes which match the specified selector string relative to the element. 60 | - `ChildNode.remove()` - Removes the element from the children list of its parent. TODO: Check whether it's `Element` or `ChildNode`. 61 | - `Element.setAttribute(attrName, value)` - Sets the value of a named attribute of the current node. 62 | - `Element.removeAttribute(attrName)` - Removes the named attribute from the current node. 63 | 64 | ## Document API 65 | 66 | - `document.getElementById(id)` - An Element object, or null if an element with the specified ID is not in the document. 67 | 68 | ## Window/Document Events 69 | 70 | - `document.addEventListener('DOMContentLoaded', callback)` 71 | - The `DOMContentLoaded` event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. Similar to `jQuery.ready()` but different because `$.ready` will execute immediately if the `DOMContentLoaded` event has already fired. 72 | - This corresponds to `document.readyState === 'interactive'`. 73 | - `window.onload = function() {}` 74 | - `window`'s `load` event is only fired after the DOM and all assets have loaded. 75 | - This corresponds to `document.readyState === 'complete'`. 76 | 77 | ## Questions 78 | 79 | **What's the difference between `Node.children` and `Node.childNodes`?** 80 | 81 | `Node.children` returns a live `HTMLCollection` of the child `elements` of `Node`. `Node.childNodes` returns a `NodeList`, an ordered collection of DOM nodes that are children of the current `Element`. `childNodes` includes all child nodes, including non-element nodes like text and comment nodes. To get a collection of only elements, use `Node.children` instead. 82 | 83 | **What's the difference between `NodeList` and `HTMLCollection`?** 84 | 85 | A `NodeList` can contain any node type, but an `HTMLCollection` is supposed to only contain `Element` nodes. `HTMLCollection` is always live and is a superset of `NodeList`. `NodeList` need not be live. 86 | 87 | **How do you convert an `HTMLCollection` or `NodeList` into an array?** 88 | 89 | ``` 90 | const nodelist = document.querySelectorAll('div'); 91 | // Array.from 92 | const divArray = Array.from(nodelist); 93 | // Array.prototype.slice 94 | const divArray2 = Array.prototype.slice.call(nodelist); // or .apply 95 | // ES2015 Spread 96 | const divArray3 = [...nodeList]; 97 | ``` 98 | 99 | ## References 100 | 101 | - https://developer.mozilla.org/en-US/docs/Web/API/Node 102 | - https://developer.mozilla.org/en-US/docs/Web/API/Element 103 | -------------------------------------------------------------------------------- /front-end/security.md: -------------------------------------------------------------------------------- 1 | Security 2 | == 3 | 4 | ## Glossary 5 | 6 | - **CORS** - Cross-Origin Resource Sharing (CORS). 7 | - **CSRF** - Cross-Site request forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. 8 | - **XSS** - Cross-site scripting (XSS). 9 | 10 | ## CORS 11 | 12 | The same-origin policy protects users by disallowing websites to retrieve information from other websites of different origins. An origin is the triple {protocol, host, port}. Two resources are considered to be of the same origin if and only if all these values are exactly the same. 13 | 14 | Cross-Origin Resource Sharing allows relaxing of the same-origin policy. CORS defines a way in which a browser and server can interact to determine whether or not it is safe to allow the cross-origin request. 15 | 16 | This standard extends HTTP with a new `Origin` request header and `Access-Control-Allow-Origin` and `Access-Control-Allow-Methods` response headers. It allows servers to use a header to explicitly list origins and HTTP methods that may request a file or to use a wildcard and allow a file to be requested by any site. `XMLHttpRequest`s to a target origin from a different source origin will be blocked if the server did not allow CORS for source origin. 17 | 18 | ## CSRF 19 | 20 | XSS vulnerabilities allow attackers to bypass essentially all CSRF preventions. 21 | 22 | #### Protection 23 | 24 | - Verifying Same Origin with Standard Headers 25 | - There are two steps to this check: 26 | 1. Determining the origin the request is coming from (source origin). 27 | 2. Determining the origin the request is going to (target origin). 28 | - Examine the `Origin`, `Referer` and `Host` Header values. 29 | - Synchronizer Tokens 30 | - The CSRF token is added as a hidden field for forms or within the URL. 31 | - Characteristics of a CSRF Token 32 | - Unique per user session 33 | - Large random value 34 | - Generated by a cryptographically secure random number generator 35 | - The server rejects the requested action if the CSRF token fails validation. 36 | - Double Cookie 37 | - When a user visits a site, the site should generate a (cryptographically strong) pseudorandom value and set it as a cookie on the user's machine. The site should require every form submission to include this pseudorandom value as a form value and also as a cookie value. When a POST request is sent to the site, the request should only be considered valid if the form value and the cookie value are the same. When an attacker submits a form on behalf of a user, he can only modify the values of the form. An attacker cannot read any data sent from the server or modify cookie values, per the same-origin policy. This means that while an attacker can send any value he wants with the form, he will be unable to modify or read the value stored in the cookie. Since the cookie value and the form value must be the same, the attacker will be unable to successfully submit a form unless he is able to guess the pseudorandom value. 38 | - The advantage of this approach is that it requires no server state; you simply set the cookie value once, then every HTTP POST checks to ensure that one of the submitted values contains the exact same cookie value. Any difference between the two means a possible XSRF attack. 39 | - Cookie-to-Header Token 40 | - On login, the web application sets a cookie containing a random token that remains the same for the whole user session 41 | - `Set-Cookie: Csrf-token=i8XNjC4b8KVok4uw5RftR38Wgp2BFwql; expires=Thu, 23-Jul-2015 10:25:33 GMT; Max-Age=31449600; Path=/` 42 | - JavaScript operating on the client side reads its value and copies it into a custom HTTP header sent with each transactional request 43 | - `X-Csrf-Token: i8XNjC4b8KVok4uw5RftR38Wgp2BFwql` 44 | - The server validates presence and integrity of the token. 45 | - Security of this technique is based on the assumption that only JavaScript running within the same origin will be able to read the cookie's value. 46 | - JavaScript running from a rogue file or email will not be able to read it and copy into the custom header. Even though the `csrf-token` cookie will be automatically sent with the rogue request, the server will be still expecting a valid `X-Csrf-Token` header. 47 | - Use of Custom Request Headers 48 | - An alternate defense which is particularly well suited for AJAX endpoints is the use of a custom request header. This defense relies on the same-origin policy (SOP) restriction that only JavaScript can be used to add a custom header, and only within its origin. By default, browsers don't allow JavaScript to make cross origin requests. Such a header can be `X-Requested-With: XMLHttpRequest`. 49 | - If this is the case for your system, you can simply verify the presence of this header and value on all your server side AJAX endpoints in order to protect against CSRF attacks. This approach has the double advantage of usually requiring no UI changes and not introducing any server side state, which is particularly attractive to REST services. You can always add your own custom header and value if that is preferred. 50 | - Require user interaction 51 | - Require a re-authentication, using a one-time token, or requiring users to complete a captcha. 52 | 53 | ###### References 54 | 55 | - [OWASP CSRF](https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)) 56 | 57 | ## HTTPS 58 | 59 | HTTPS is HTTP over SSL/TLS. Servers and clients still speak exactly the same HTTP to each other, but over a secure SSL connection that encrypts and decrypts their requests and responses. The SSL layer has 2 main purposes: 60 | 61 | 1. Verifying that you are talking directly to the server that you think you are talking to. 62 | 1. Ensuring that only the server can read what you send it and only you can read what it sends back. 63 | 64 | #### TLS Handshake 65 | 66 | // TODO. Crosscheck and add in more details. 67 | 68 | 1. The client computer sends a `ClientHello` message to the server with its Transport Layer Security (TLS) version, list of cipher algorithms and compression methods available. 69 | 1. The server replies with a `ServerHello` message to the client with the TLS version, selected cipher, selected compression methods and the server's public certificate signed by a CA (Certificate Authority). The certificate contains a public key that will be used by the client to encrypt the rest of the handshake until a symmetric key can be agreed upon. 70 | 1. The client verifies the server digital certificate against its list of trusted CAs. If trust can be established based on the CA, the client generates a string of pseudo-random bytes and encrypts this with the server's public key. These random bytes can be used to determine the symmetric key. 71 | 1. The server decrypts the random bytes using its private key and uses these bytes to generate its own copy of the symmetric master key. 72 | 1. The client sends a `Finished` message to the server, encrypting a hash of the transmission up to this point with the symmetric key. 73 | 1. The server generates its own hash, and then decrypts the client-sent hash to verify that it matches. If it does, it sends its own `Finished` message to the client, also encrypted with the symmetric key. 74 | 1. From now on the TLS session transmits the application (HTTP) data encrypted with the agreed symmetric key. 75 | 76 | #### Downsides of HTTPS 77 | 78 | - TLS handshake computational and latency overhead. 79 | - Encryption and decryption requires more computation power and bandwidth. 80 | 81 | ###### References 82 | 83 | - https://blog.hartleybrody.com/https-certificates/ 84 | - https://github.com/alex/what-happens-when#tls-handshake 85 | - http://robertheaton.com/2014/03/27/how-does-https-actually-work/ 86 | 87 | ## XSS 88 | 89 | XSS vulnerabilities allow attackers to bypass essentially all CSRF preventions. 90 | 91 | ```js 92 | const name = ""; 93 | el.innerHTML = name; 94 | ``` 95 | 96 | http://shebang.brandonmintern.com/foolproof-html-escaping-in-javascript/ 97 | 98 | ## Session hijacking 99 | 100 | - https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies 101 | - https://www.nczonline.net/blog/2009/05/12/cookies-and-security/ 102 | 103 | 104 | ## Framebusting 105 | 106 | https://seclab.stanford.edu/websec/framebusting/framebust.pdf 107 | 108 | ## API 109 | 110 | https://github.com/shieldfy/API-Security-Checklist 111 | -------------------------------------------------------------------------------- /non-technical/negotiation.md: -------------------------------------------------------------------------------- 1 | Negotiation 2 | == 3 | 4 | ### Ten Rules of Negotiation 5 | 6 | Key points extracted from "Ten Rules for Negotiating a Job Offer" [Part 1](http://haseebq.com/my-ten-rules-for-negotiating-a-job-offer/) and [Part 2](https://haseebq.com/how-not-to-bomb-your-offer-negotiation/) by Haseeb Qureshi. 7 | 8 | #### Get everything in writing 9 | 10 | Note down EVERYTHING on your phone call with the recruiters as they may be helpful later on. Even if there are things that are not directly monetary, if they relate to the job, write them down. If they tell you "we're working on porting the front-end to Angular," write that down. If they say they have 20 employees, write that down. You want as much information as you can. You'll forget a lot of this stuff, and it's going to be important in informing your final decision. 11 | 12 | #### Always keep the door open 13 | 14 | Never give up your negotiating power until you're absolutely ready to make an informed, deliberate final decision. This means your job is to traverse as many of these decision points as possible without giving up the power to continue negotiating. Very frequently, your interlocutor will try to trick you into making a decision, or tie you to a decision you didn't commit to. You must keep verbally jiu-jitsu-ing out of these antics until you're actually ready to make your final decision. 15 | 16 | #### Information is power 17 | 18 | To protect your power in the negotiation, you must protect information as much as possible. A corollary of this rule is that you should not reveal to companies what you're currently making. So given this offer, don't ask for more money or equity or anything of the sort. Don't comment on any specific details of the offer except to clarify them. Companies will ask about your current compensation at different stages in the process—some before they ever interview you, some after they decide to make you an offer. But be mindful of this, and protect information. 19 | 20 | > "Yeah, [COMPANY_NAME] sounds great! I really thought this was a good fit, and I'm glad that you guys agree. Right now I'm talking with a few other companies so I can't speak to the specific details of the offer until I'm done with the process and get closer to making a decision. But I'm sure we'll be able to find a package that we're both happy with, because I really would love to be a part of the team." 21 | 22 | #### Always be positive 23 | 24 | Even if the offer is bad, it's extremely important to remain positive and excited about the company. This is because your excitement is one of your most valuable assets in a negotiation. 25 | 26 | Despite whatever is happening in the negotiation, give the company the impression that 1) you still like the company, and that 2) you're still excited to work there, even if the numbers or the money or the timing is not working out. Generally the most convincing thing to signal this is to reiterate you love the mission, the team, or the problem they're working on, and really want to see things work out. 27 | 28 | #### Don't be the decision maker 29 | 30 | Even if you don't particularly care what your friends/family/husband/mother thinks, by mentioning them, you're no longer the only person the recruiter needs to win over. There's no point in them trying to bully and intimidate you; the "true decision-maker" is beyond their reach. This is a classic technique in customer support and remediation. It's never the person on the phone's fault, they're just some poor schmuck doing their job. It's not their decision to make. This helps to defuse tension and give them more control of the situation. 31 | 32 | > I'll look over some of these details and discuss it with my [FAMILY/CLOSE_FRIENDS/SIGNIFICANT_OTHER]. I'll reach out to you if I have any questions. Thanks so much for sharing the good news with me, and I'll be in touch! 33 | 34 | It's much harder to pressure someone if they're not the final decision-maker. So take advantage of that. 35 | 36 | #### Have alternatives 37 | 38 | If you're already in the pipeline with other companies (which you should be if you're doing it right), you should proactively reach out and let them know that you've just received an offer. Try to build a sense of urgency. Regardless of whether you know the expiration date, all offers expire at some point, so take advantage of that. 39 | 40 | > Hello [PERSON], 41 | > 42 | > I just wanted to update you on my own process. I've just received an offer from [COMPANY] which is quite strong. That said, I'm really excited about [YOUR AMAZING COMPANY] and really want to see if we can make it work. Since my timeline is now compressed, is there anything you can do to expedite the process? 43 | 44 | Should you specifically mention the company that gave you an offer? Depends. If it's a well-known company or a competitor, then definitely mention it. If it's a no-name or unsexy company, you should just say you received an offer. If it's expiring soon, you should mention that as well. 45 | 46 | Either way, send out a letter like this to every single company you're talking to. No matter how hopeless or pointless you think your application is, you want to send this signal to everyone who is considering you in the market. 47 | 48 | Companies care that you've received other offers. They care because each company knows that their own process is noisy, and the processes of most other companies are also noisy. But a candidate having multiple offers means that they have multiple weak signals in their favor. Combined, these converge into a much stronger signal than any single interview. It's like knowing that a student has a strong SAT score, and GPA, and won various scholarships. Sure, it's still possible that they're a dunce, but it's much harder for that to be true. 49 | 50 | This is not to say that companies respond proportionally to these signals, or that they don't overvalue credentials and brands. They do. But caring about whether you have other offers and valuing you accordingly is completely rational. 51 | 52 | Tell other companies that you've received offers. Give them more signals so that they know you're a valued and compelling candidate. And understand why this changes their mind about whether to interview you. 53 | 54 | Your goal should be to have as many offers overlapping at the same time as possible. This will maximize your window for negotiating. 55 | 56 | Have a strong BATNA (Best Alternative To a Negotiated Agreement) and communicate it. 57 | 58 | > I 've received another offer from [OTHER CORP] that's very compelling on salary, but I really love the mission of [YOUR COMPANY] and think that it would overall be a better fit for me. 59 | 60 | > I'm also considering going back to grad school and getting a Master's degree in Postmodern Haberdashery. I'm excited about [YOUR COMPANY] though and would love to join the team, but the package has to make sense if I'm going to forego a life of ironic hatmaking. 61 | 62 | #### Proclaim reasons for everything 63 | 64 | It's kind of a brain-hack, both for yourself and for your negotiating partner. Just stating a reason (any reason) makes your request feel human and important. It's not you being greedy, it's you trying to fulfill your goals. 65 | 66 | The more unobjectionable and sympathetic your reason, the better. If it's medical expenses, or paying off student loans, or taking care of family, you'll bring tears to their eyes. 67 | 68 | Just go with it, state a reason for everything, and you'll find recruiters more willing to become your advocate. 69 | 70 | #### Be motivated by more than just money 71 | 72 | You should be motivated by money too of course, but it should be one among many dimensions you're optimizing for. How much training you get, what your first project will be, which team you join, or even who your mentor will be—these are all things you can and should negotiate. 73 | 74 | Of course, to negotiate well you need to understand the other side's preferences. You want to make the deal better for both of you. 75 | 76 | #### Understand what they value 77 | 78 | Remember that you can always get salary raises as you continue to work at the company, but there's only one point at which you can get a signing bonus. 79 | 80 | The easiest thing for a company to give though is stock (if the company offers stock). Companies like giving stock because it invests you in the company and aligns interests. It also shifts some of the risk from the company over to you and burns less cash. 81 | 82 | #### Be winnable 83 | 84 | This is more than just giving the company the impression that you like them (which you continually should). But more so that you must give any company you're talking to a clear path on how to win you. Don't bullshit them or play stupid games. Be clear and unequivocal with your preferences and timeline. 85 | 86 | Don't waste their time or play games for your own purposes. Even if the company isn't your dream company, you must be able to imagine at least some package they could offer you that would make you sign. If not, politely turn them down. 87 | -------------------------------------------------------------------------------- /non-technical/behavioral.md: -------------------------------------------------------------------------------- 1 | Behavioral 2 | == 3 | 4 | Learn the [STAR](https://en.wikipedia.org/wiki/Situation,_task,_action,_result) format. From Wikipedia: 5 | 6 | - **Situation** - The interviewer wants you to present a recent challenge and situation in which you found yourself. 7 | - **Task** - What were you required to achieve? The interviewer will be looking to see what you were trying to achieve from the situation. Some performance development methods[1] use “Target” rather than “Task”. Job interview candidates who describe a “Target” they set themselves instead of an externally imposed “Task” emphasize their own intrinsic motivation to perform and to develop their performance. 8 | - **Action** - What did you do? The interviewer will be looking for information on what you did, why you did it and what the alternatives were. 9 | - **Results** - What was the outcome of your actions? What did you achieve through your actions and did you meet your objectives? What did you learn from this experience and have you used this learning since? 10 | 11 | ## General 12 | 13 | - Why do you want to work for X company? 14 | - Why do you want to leave your current/last company? 15 | - What are you looking for in your next role? 16 | - Tell me about a time when you had a conflict with a co-worker. 17 | - Tell me about a time in which you had a conflict and needed to influence somebody else. 18 | - What project are you currently working on? 19 | - What is the most challenging aspect of your current project? 20 | - What was the most difficult bug that you fixed in the past 6 months? 21 | - How do you tackle challenges? Name a difficult challenge you faced while working on a project, how you overcame it, and what you learned. 22 | - What are you excited about? 23 | - What frustrates you? 24 | - Imagine it is your first day here at the company. What do you want to work on? What features would you improve on? 25 | - What are the most interesting projects you have worked on and how might they be relevant to this company's environment? 26 | - Tell me about a time you had a disagreement with your manager. 27 | - Talk about a project you are most passionate about, or one where you did your best work. 28 | - What does your best day of work look like? 29 | - What is something that you had to push for in your previous projects? 30 | - What is the most constructive feedback you have received in your career? 31 | - What was one thing you had to persevere for multiple months? 32 | 33 | ## Airbnb 34 | 35 | Source: [Glassdoor](https://www.glassdoor.com/Interview/Airbnb-Interview-Questions-E391850.htm) 36 | 37 | While loving to travel or appreciating Airbnb's growth may be good answers, try to demonstrate the deep connection you have with the product. 38 | 39 | - What does "belong anywhere" mean to you? 40 | - What large problems in the world would you solve today? 41 | - Why do you like Airbnb? 42 | - If you had an unlimited budget and you could buy one gift for one person, what would you buy and who would you buy it for? 43 | - If you had an unlimited budget and you could go somewhere, where would you go? 44 | - Share one of your trips with us. 45 | - What is the most challenging project in or out of school that you have worked on in the last 6 months. 46 | - What is the thing that you don't want from your last internship/job? 47 | - Give me an example of when you've been a good host. 48 | - One thing you would like to remove from the Airbnb experience. 49 | - What is something new that you can teach your interviewer in a few minutes? 50 | - Tell me about why you want to work here. 51 | - What is the best gift you have ever given or received? 52 | - Tell me about a time you were uncomfortable and how you dealt with it. 53 | - Explain a project that you worked on recently. 54 | - What do you think of Airbnb? 55 | - Tell me something about yourself and why you'd be a good fit for the position. 56 | - Name a situation where you were impressed by a company's customer service. 57 | - How did you work with senior management on large projects as well as multiple internal teams? 58 | - Tell me about a time you had to give someone terrible news. 59 | - If you were a gerbil, which gerbil would you be? 60 | - What excites you about the company? 61 | - How does Airbnb impact our guests and hosts? 62 | - What part of our mission resonates the most with you? 63 | 64 | ## Amazon 65 | 66 | Source: [Glassdoor](https://www.glassdoor.com/Interview/Amazon-Interview-Questions-E6036.htm) 67 | 68 | - How do you deal with a failed deadline? 69 | - Why do you want to work for Amazon? 70 | - Talked about a situation where you had a conflict with a teammate. 71 | - In my professional experience have you worked on something without getting approval from your manager? 72 | - Tell me a situation where you would have done something differently from what you actually did. 73 | - What is the most exceedingly bad misstep you at any point made? 74 | - Describe what Human Resource means to you. 75 | - How would you improve Amazon's website? 76 | 77 | ## Dropbox 78 | 79 | Source: [Glassdoor](https://www.glassdoor.com/Interview/Dropbox-Interview-Questions-E415350.htm) 80 | 81 | - Talk about your favorite project. 82 | - If you were hired here what would you do? 83 | - State an experience about how you solved a technical problem. Be specific about the diagnosis and process. 84 | 85 | ## Hired 86 | 87 | Source: [Glassdoor](https://hired.com/blog/candidates/10-top-interview-questions-how-to-answer/) 88 | 89 | - Tell me about yourself. 90 | - What is your biggest strength and area of growth? 91 | - Why are you interested in this opportunity? 92 | - What are your salary expectations? 93 | - Why are you looking to leave your current company? 94 | - What is your biggest strength and area of growth? 95 | - Tell me about a time your work responsibilities got a little overwhelming. What did you do? 96 | - Give me an example of a time when you had a difference of opinion with a team member. How did you handle that? 97 | - Tell me about a challenge you faced recently in your role. How did you tackle it? What was the outcome? 98 | - Where do you want to be in five years? 99 | - Tell me about a time you needed information from someone who wasn't responsive. What did you do? 100 | 101 | ## Lyft 102 | 103 | Source: [Glassdoor](https://www.glassdoor.com/Interview/Lyft-Interview-Questions-E700614.htm) 104 | 105 | - Tell me about your most interesting/challenging project to date. 106 | - Why Lyft? What are you looking for in the next role? 107 | 108 | ## Palantir 109 | 110 | Source: [Glassdoor](https://www.glassdoor.com/Interview/Palantir-Technologies-Interview-Questions-E236375.htm) 111 | 112 | - How do you deal with difficult coworkers? Think about specific instances where you resolved conflicts. 113 | - How did you win over the difficult employees? 114 | - Tell me about an analytical problem that you have worked on in the past. 115 | - What are your three strengths and three weaknesses? 116 | - If you were in charge of picking projects for Palantir, what problem would you try to solve? 117 | - **What is something 90% of people disagree with you about?** 118 | - What are some of the best and worse things about your current company? 119 | - **What is broken around you?** 120 | - What would your manager say about you? 121 | - Describe Palantir to your grandmother. 122 | - Teach me something you've learned? 123 | - Tell me a time when you predicted something? 124 | - If your supervisors were to rate you on a scale of 1-10 what would they rate you? 125 | - What was the most fun thing you did recently? 126 | - Tell me the story of how you became who you are today and what made you apply to Palantir. 127 | 128 | ## Slack 129 | 130 | Source: [Glassdoor](https://www.glassdoor.com/Interview/Slack-Interview-Questions-E950758.htm) 131 | 132 | - Tell me something about your internship. 133 | - Why do you want to join Slack? 134 | - Tell me about your past projects. 135 | - Explain me your toughest project and the working architecture. 136 | - Apart from technical knowledge what did you learn during your internship? 137 | - If someone has a different viewpoint to do a project like different programming language, how would handle this situation? 138 | - What are your most interesting subjects and why? 139 | - Did you find any bug in Slack? 140 | - What is your favorite feature and why? 141 | 142 | ## Stack Overflow 143 | 144 | Source: [Glassdoor](https://hired.com/blog/candidates/10-top-interview-questions-how-to-answer/) 145 | 146 | - What have you built? 147 | - What is the hardest technical problem you have run into? 148 | - How did you solve it? 149 | - Where do you see yourself in 5 years? 150 | - Why do you want to work here? 151 | - How do you handle disagreements with coworkers? 152 | 153 | ## Stripe 154 | 155 | Source: [Glassdoor](https://www.glassdoor.com/Interview/Stripe-Interview-Questions-E671932.htm) 156 | 157 | - How do you stay up to date with the latest technologies? 158 | - Explain a project that you worked on recently that was difficult. 159 | - Where do you see yourself in five years? 160 | 161 | ## Twitter 162 | 163 | Source: [Glassdoor](https://www.glassdoor.com/Interview/Twitter-Interview-Questions-E100569.htm) 164 | 165 | - What would your previous boss say your biggest strength was? 166 | -------------------------------------------------------------------------------- /design/news-feed.md: -------------------------------------------------------------------------------- 1 | News Feed 2 | == 3 | 4 | ## Variants 5 | 6 | - Design Facebook news feed. 7 | - Design Twitter news feed. 8 | - Design Quora feed. 9 | - Design Instagram feed. 10 | 11 | ## Requirements Gathering 12 | 13 | - What is the intended platform? 14 | - Mobile (mobile web or native)? Web? Desktop? 15 | - What features are required? 16 | - CRUD posts. 17 | - Commenting on posts. 18 | - Sharing posts. 19 | - Trending posts? 20 | - Tag people? 21 | - Hashtags? 22 | - What is in a news feed post? 23 | - Author. 24 | - Content. 25 | - Media. 26 | - Tags? 27 | - Hashtags? 28 | - Comments/Replies. 29 | - Operations: 30 | - CRUD 31 | - Commenting/replying to a post. 32 | - What is in a news feed? 33 | - Sequence of posts. 34 | - Query pattern: query for a user's ranked news feed. 35 | - Operations: 36 | - Append - Fetch more posts. 37 | - Delete - I don't want to see this. 38 | - Which metrics should we optimize for? 39 | - User retention. 40 | - Ads revenue. 41 | - Fast loading time. 42 | - Bandwidth. 43 | - Server costs. 44 | 45 | ## Core Components 46 | 47 | TODO 48 | 49 | ## Data modeling 50 | 51 | - What kind of database to use? 52 | - Data is quite structured. Would go with SQL. 53 | - Design the necessary tables, its columns and its relations. 54 | - `users` 55 | - `posts` 56 | - `likes` 57 | - `follows` 58 | - `comments` 59 | 60 | > There are two basic objects: user and feed. For user object, we can store userID, name, registration date and so on so forth. And for feed object, there are feedId, feedType, content, metadata etc., which should support images and videos as well. 61 | > 62 | > If we are using a relational database, we also need to model two relations: user-feed relation and friend relation. The former is pretty straightforward. We can create a user-feed table that stores userID and corresponding feedID. For a single user, it can contain multiple entries if he has published many feeds. 63 | > 64 | > For friend relation, adjacency list is one of the most common approaches. If we see all the users as nodes in a giant graph, edges that connect nodes denote friend relation. We can use a friend table that contains two userIDs in each entry to model the edge (friend relation). By doing this, most operations are quite convenient like fetch all friends of a user, check if two people are friends. 65 | > 66 | > The system will first get all userIDs of friends from friend table. Then it fetches all feedIDs for each friend from user-feed table. Finally, feed content is fetched based on feedID from feed table. You can see that we need to perform 3 joins, which can affect performance. 67 | > 68 | > A common optimization is to store feed content together with feedID in user-feed table so that we don't need to join the feed table any more. This approach is called denormalization, which means by adding redundant data, we can optimize the read performance (reducing the number of joins). 69 | > 70 | > The disadvantages are obvious: 71 | > - Data redundancy. We are storing redundant data, which occupies storage space (classic time-space trade-off). 72 | > - Data consistency. Whenever we update a feed, we need to update both feed table and user-feed table. Otherwise, there is data inconsistency. This increases the complexity of the system. 73 | > - Remember that there's no one approach always better than the other (normalization vs denormalization). It's a matter of whether you want to optimize for read or write. 74 | 75 | ## Feed Display 76 | 77 | - The most straightforward way is to fetch posts from all the people you follow and render them sorted by time. 78 | - There can be many posts to fetch. How many posts should you fetch? 79 | - What are the pagination approaches and the pros and cons of each approach? 80 | - Offset by page size 81 | - Offset by time 82 | - What data should the post contain when you initially fetch them? 83 | - Lazy loading approach for loading associated data: media, comments, people who liked the post. 84 | - Media 85 | - If the post contains media such as images and videos, how should they be handled? Should they be loaded on the spot? 86 | - A better way would be to fetch images only when they are about to enter the viewport. 87 | - Videos should not autoplay. Only fetch the thumbnail for the video, and only play the video when user clicks play. 88 | - If the content is being refetched, the media should be cached and not fetched over the wire again. This is especially important on mobile connections where data can be expensive. 89 | - Comments 90 | - Should you fetch all the comments for a post? For posts by celebrities, they can contain a few hundred or thousand comments. 91 | - Maybe fetch the top few comments and display them under the post, and the user is given the choice to "show all comments". 92 | - How does the user request for new content? 93 | - Infinite scrolling. 94 | - User has to tap next page. 95 | 96 | ## Feed Ranking 97 | 98 | - First select features/signals that are relevant and then figure out how to combine them to calculate a final score. 99 | - How do you show the relevant posts that the user is interested in? 100 | - Chronological - While a chronological approach works, it may not be the most engaging approach. For example, if a person posts 30 times within the last hour, his followers will have their news feed clogged up with his posts. Maybe set a cap on the number of time a person's posts can appear within the feed. 101 | - Popularity - How many likes and comments does the post have? Does the user usually like posts by that person? 102 | - How do you determine which are the more important posts? A user might be more interested in a few-hour old post from a good friend than a very recent post from an acquaintance. 103 | - A common strategy is to calculate a post score based on various features and rank posts by its score. 104 | - Prior to 2013, Facebook was using the [EdgeRank](https://www.wikiwand.com/en/EdgeRank) algorithm to determine what articles should be displayed in a user's News Feed. 105 | - Edge Rank basically is using three signals: affinity score, edge weight and time decay. 106 | - Affinity score (u) - For each news feed, affinity score evaluates how close you are with this user. For instance, you are more likely to care about feed from your close friends instead of someone you just met once. 107 | - Edge weight (e) - Edge weight basically reflects importance of each edge. For instance, comments are worth more than likes. 108 | - Time decay (d) - The older the story, the less likely users find it interesting. 109 | - Affinity score 110 | - Various factors can be used to reflect how close two people are. First of all, explicit interactions like comment, like, tag, share, click etc. are strong signals we should use. Apparently, each type of interaction should have different weight. For instance, comments should be worth much more than likes. 111 | - Secondly, we should also track the time factor. Perhaps you used to interact with a friend quite a lot, but less frequent recently. In this case, we should lower the affinity score. So for each interaction, we should also put the time decay factor. 112 | - A good ranking system can improve some core metrics - user retention, ads revenue, etc. 113 | 114 | ## Feed Publishing 115 | 116 | TODO. Refer to http://blog.gainlo.co/index.php/2016/04/05/design-news-feed-system-part-2/. 117 | 118 | ## Additional Features 119 | 120 | #### Tagging feature 121 | 122 | - Have a `tags` table that stores the relation between a post and the people tagged in it. 123 | 124 | #### Sharing feature 125 | 126 | - Add a column to `posts` table called `original_post_id`. 127 | - What should happen when the original post is deleted? 128 | - The shared `posts` have to be deleted too. 129 | 130 | #### Notifications feature 131 | 132 | - When should notifications happen? 133 | - Can the user subscribe to only certain types of notifications? 134 | 135 | #### Trending feature 136 | 137 | - What constitutes trending? What signals would you look at? What weight would you give to each signal? 138 | - Most frequent hashtags over the last N hours. 139 | - Hottest search queries. 140 | - Fetch the recent most popular feeds and extract some common words or phrases. 141 | 142 | #### Search feature 143 | 144 | - How would you index the data? 145 | 146 | ## Scalability 147 | 148 | - Master-slave replication. 149 | - Write to master database and read from replica databases/in-memory data store. 150 | - Post contents are being read more than they are updated. It is acceptable to have a slight lag between a user updating a post and followers seeing the updated content. Tweets are not even editable. 151 | - Data for real-time queries should be in memory, disk is for writes only. 152 | - Pre-computation offline. 153 | - Tracking number of likes and comments. 154 | - Expensive to do a `COUNT` on the `likes` and `comments` for a post. 155 | - Use Redis/Memcached for keeping track of how many likes/comments a post has. Increment when there's new activity, decrement when someone unlikes/deletes the comment. 156 | - Load balancer in front of your API servers. 157 | - Partitioning the data. 158 | 159 | ###### References 160 | 161 | - [Design News Feed System (Part 1)](http://blog.gainlo.co/index.php/2016/03/29/design-news-feed-system-part-1-system-design-interview-questions/) 162 | - [Design News Feed System (Part 1)](http://blog.gainlo.co/index.php/2016/04/05/design-news-feed-system-part-2/) 163 | - [Etsy Activity Feeds Architecture](https://www.slideshare.net/danmckinley/etsy-activity-feeds-architecture) 164 | - [Big Data in Real-Time at Twitter](https://www.slideshare.net/nkallen/q-con-3770885) 165 | -------------------------------------------------------------------------------- /front-end/accessibility.md: -------------------------------------------------------------------------------- 1 | Accessibility 2 | == 3 | 4 | ## Glossary 5 | 6 | - **Accessibility** - 7 | - **WAI-ARIA** - Web Accessibility Initiative - Accessible Rich Internet Applications. Commonly shortened to ARIA. 8 | 9 | ## What is Accessibility? 10 | 11 | Making sure that the content and the websites we create are usable to people with impairments or disabilities. 12 | 13 | ## WebAIM Checklist 14 | 15 | The following is a checklist that contains recommendations for implementing HTML-related principles and techniques for those seeking WCAG 2.0 conformance (it is NOT the Web Content Accessibility Guidelines (WCAG) 2.0). 16 | 17 | - **Perceivable** - Web content is made available to the senses - sight, hearing, and/or touch. 18 | - Text Alternatives: Provide text alternatives for any non-text content. 19 | - Time-based Media: Provide alternatives for time-based media. 20 | - Adaptable: Create content that can be presented in different ways (for example simpler layout) without losing information or structure. 21 | - Distinguishable: Make it easier for users to see and hear content including separating foreground from background. 22 | - **Operable** - Interface forms, controls, and navigation are operable. 23 | - Keyboard Accessible: Make all functionality available from a keyboard. 24 | - Enough Time: Provide users enough time to read and use content. 25 | - Seizures: Do not design content in a way that is known to cause seizures. 26 | - Navigable: Provide ways to help users navigate, find content, and determine where they are. 27 | - **Understandable** - Content and interface are understandable. 28 | - Readable: Make text content readable and understandable. 29 | - Predictable: Make Web pages appear and operate in predictable ways. 30 | - Input Assistance: Help users avoid and correct mistakes. 31 | - **Robust** - Content can be used reliably by a wide variety of user agents, including assistive technologies. 32 | - Compatible: Maximize compatibility with current and future user agents, including assistive technologies. 33 | 34 | **Source:** http://webaim.org/standards/wcag/checklist 35 | 36 | ## Focus 37 | 38 | - Making sure your application has a sensible tab order is important. 39 | - HTML forms and inputs are focusable and handle keyboard events by default. 40 | - Focus tab order relies on the DOM order in the HTML. 41 | - Be careful when using CSS when changing the order of elements on the screen, it can cause the order to be unintuitive and messy. 42 | - `tabindex` attribute: 43 | - `-1`: Not in the natural tab order, but programatically focusable using JavaScript with `focus()` method. Useful for off-screen content which later appears on screen. Children elements are **NOT** pulled out of the tab order. 44 | - `0`: In the natural tab order and can be programatically focused. 45 | - `1` (bigger than 1): In the natural tab order but jumped in front of the tab order regardless of where it is in the DOM. It can be considered an anti-pattern. 46 | - Add focus behavior to interactive controls, like buttons, tabs, dropdowns, stuff that users will interactive with. 47 | - Use skip links to allow users to skip directly to the main content without having to tab through all the navigation. 48 | - `document.activeElement` is useful in tracking the current element that has focus on. 49 | 50 | ## Semantics 51 | 52 | - Using proper labeling not only helps accessibility but it makes the element easier to target for all users! 53 | - Use `