Format all files

pull/89/head
Panayiotis Lipiridis 8 years ago
parent 789add546f
commit 1311262d8a

@ -15,20 +15,20 @@
Carefully curated content to help you ace your next technical interview, with a focus on algorithms and the front end domain. System design questions are in-progress. Besides the usual algorithm questions, other **awesome** stuff includes:
- [How to prepare](preparing) for coding interviews
- [Interview Cheatsheet](preparing/cheatsheet.md) - Straight-to-the-point Do's and Don'ts 🆕
- [Algorithm tips and the best practice questions](algorithms) categorized by topic
- ["Front-end Job Interview Questions" answers](front-end/interview-questions.md)
- [Interview formats](non-technical/interview-formats.md) of the top tech companies
- [Behavioral questions](non-technical/behavioral.md) categorized by companies
- [Good questions to ask your interviewers](non-technical/questions-to-ask.md) at the end of the interviews
- [Helpful resume tips](non-technical/resume.md) to get your resume noticed and the Do's and Don'ts
* [How to prepare](preparing) for coding interviews
* [Interview Cheatsheet](preparing/cheatsheet.md) - Straight-to-the-point Do's and Don'ts 🆕
* [Algorithm tips and the best practice questions](algorithms) categorized by topic
* ["Front-end Job Interview Questions" answers](front-end/interview-questions.md)
* [Interview formats](non-technical/interview-formats.md) of the top tech companies
* [Behavioral questions](non-technical/behavioral.md) categorized by companies
* [Good questions to ask your interviewers](non-technical/questions-to-ask.md) at the end of the interviews
* [Helpful resume tips](non-technical/resume.md) to get your resume noticed and the Do's and Don'ts
This handbook is pretty new and help from you in contributing content would be very much appreciated!
## Why do I want this?
This repository has *practical* content that covers all phases of a technical interview, from applying for a job to passing the interviews to offer negotiation. Technically competent candidates might still find the non-technical content helpful as well.
This repository has _practical_ content that covers all phases of a technical interview, from applying for a job to passing the interviews to offer negotiation. Technically competent candidates might still find the non-technical content helpful as well.
## Who is this for?
@ -42,21 +42,21 @@ Also, existing resources focus mainly on algorithm questions and lack coverage f
## Contents
- **[Preparing for a Coding Interview](preparing)**
- [Interview cheatsheet](preparing/cheatsheet.md) - Straight-to-the-point Do's and Don'ts
- **[Algorithm Questions](algorithms)** - Questions categorized by topics
- **[Design Questions](design)**
- **[Front-end Study Notes](front-end)** - Summarized notes on the various aspects of front-end
- [Front-end Job Interview Questions and Answers](front-end/interview-questions.md) 🔥⭐
- **[Non-Technical Tips](non-technical)** - Random non-technical tips that cover behavioral and psychological aspects, interview formats and "Do you have any questions for me?"
- [Resume Tips](non-technical/resume.md)
- [Behavioral Questions](non-technical/behavioral.md)
- [Interview Formats](non-technical/interview-formats.md)
- [Psychological Tricks](non-technical/psychological-tricks.md)
- [Questions to Ask](non-technical/questions-to-ask.md)
- [Negotiation Tips](non-technical/negotiation.md)
- **[Utilities](utilities)** - Snippets of algorithms/code that will help in coding questions
- **UPDATE** - Check out [Lago](https://github.com/yangshun/lago), which is a Data Structures and Algorithms library that contains more high-quality implementations with 100% test coverage.
* **[Preparing for a Coding Interview](preparing)**
* [Interview cheatsheet](preparing/cheatsheet.md) - Straight-to-the-point Do's and Don'ts
* **[Algorithm Questions](algorithms)** - Questions categorized by topics
* **[Design Questions](design)**
* **[Front-end Study Notes](front-end)** - Summarized notes on the various aspects of front-end
* [Front-end Job Interview Questions and Answers](front-end/interview-questions.md) 🔥⭐
* **[Non-Technical Tips](non-technical)** - Random non-technical tips that cover behavioral and psychological aspects, interview formats and "Do you have any questions for me?"
* [Resume Tips](non-technical/resume.md)
* [Behavioral Questions](non-technical/behavioral.md)
* [Interview Formats](non-technical/interview-formats.md)
* [Psychological Tricks](non-technical/psychological-tricks.md)
* [Questions to Ask](non-technical/questions-to-ask.md)
* [Negotiation Tips](non-technical/negotiation.md)
* **[Utilities](utilities)** - Snippets of algorithms/code that will help in coding questions
* **UPDATE** - Check out [Lago](https://github.com/yangshun/lago), which is a Data Structures and Algorithms library that contains more high-quality implementations with 100% test coverage.
## Related
@ -68,5 +68,5 @@ There are no formal contributing guidelines at the moment as things are still in
## Maintainers
- [Yangshun Tay](https://github.com/yangshun)
- [Louie Tan](https://github.com/louietyj)
* [Yangshun Tay](https://github.com/yangshun)
* [Louie Tan](https://github.com/louietyj)

@ -1,5 +1,4 @@
Algorithm Questions
==
# Algorithm Questions
This section dives deep into practical tips for specific topics of algorithms and data structures which appear frequently in coding questions. Many algorithm questions involve techniques that can be applied to questions of similar nature. The more techniques you have in your arsenal, the higher the chances of passing the interview. They may lead you to discover corner cases you might have missed out or even lead you towards the optimal approach!
@ -9,23 +8,23 @@ If you are interested in how data structures are implemented, check out [Lago](h
## Contents
- [Array](array.md)
- [Dynamic Programming and Memoization](dynamic-programming.md)
- [Geometry](geometry.md)
- [Graph](graph.md)
- [Hash Table](hash-table.md)
- [Heap](heap.md)
- [Interval](interval.md)
- [Linked List](linked-list.md)
- [Math](math.md)
- [Matrix](matrix.md)
- [Object-Oriented Programming](oop.md)
- [Permutation](permutation.md)
- [Queue](queue.md)
- [Sorting and Searching](sorting-searching.md)
- [Stack](stack.md)
- [String](string.md)
- [Tree](tree.md)
* [Array](array.md)
* [Dynamic Programming and Memoization](dynamic-programming.md)
* [Geometry](geometry.md)
* [Graph](graph.md)
* [Hash Table](hash-table.md)
* [Heap](heap.md)
* [Interval](interval.md)
* [Linked List](linked-list.md)
* [Math](math.md)
* [Matrix](matrix.md)
* [Object-Oriented Programming](oop.md)
* [Permutation](permutation.md)
* [Queue](queue.md)
* [Sorting and Searching](sorting-searching.md)
* [Stack](stack.md)
* [String](string.md)
* [Tree](tree.md)
## General Tips
@ -45,12 +44,12 @@ Is the algorithm meant to be run multiple times, for example in a web server? If
Use a mix of functional and imperative programming paradigms:
- Write pure functions as much as possible.
- Pure functions are easier to reason about and can help to reduce bugs in your implementation.
- Avoid mutating the parameters passed into your function especially if they are passed by reference unless you are sure of what you are doing.
- However, functional programming is usually expensive in terms of space complexity because of non-mutation and the repeated allocation of new objects. On the other hand, imperative code is faster because you operate on existing objects. Hence you will need to achieve a balance between accuracy vs efficiency, by using the right amount of functional and imperative code where appropriate.
- Avoid relying on and mutating global variables. Global variables introduce state.
- If you have to rely on global variables, make sure that you do not mutate it by accident.
* Write pure functions as much as possible.
* Pure functions are easier to reason about and can help to reduce bugs in your implementation.
* Avoid mutating the parameters passed into your function especially if they are passed by reference unless you are sure of what you are doing.
* However, functional programming is usually expensive in terms of space complexity because of non-mutation and the repeated allocation of new objects. On the other hand, imperative code is faster because you operate on existing objects. Hence you will need to achieve a balance between accuracy vs efficiency, by using the right amount of functional and imperative code where appropriate.
* Avoid relying on and mutating global variables. Global variables introduce state.
* If you have to rely on global variables, make sure that you do not mutate it by accident.
Generally, to improve the speed of a program, we can either choose a more appropriate data structure/algorithm or use more memory. It's a classic space/time tradeoff.
@ -82,9 +81,9 @@ When you are given two sequences to process, it is common to have one index per
#### Corner Cases
- Empty sequence.
- Sequence with 1 or 2 elements.
- Sequence with repeated elements.
* Empty sequence.
* Sequence with 1 or 2 elements.
* Sequence with repeated elements.
## Array
@ -100,22 +99,22 @@ If you are given a sequence and the interviewer asks for O(1) space, it might be
#### Practice Questions
- [Two Sum](https://leetcode.com/problems/two-sum/)
- [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)
- [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/)
- [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/)
- [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/)
- [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/)
- [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/)
- [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/)
- [3Sum](https://leetcode.com/problems/3sum/)
- [Container With Most Water](https://leetcode.com/problems/container-with-most-water/)
* [Two Sum](https://leetcode.com/problems/two-sum/)
* [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)
* [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/)
* [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/)
* [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/)
* [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/)
* [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/)
* [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/)
* [3Sum](https://leetcode.com/problems/3sum/)
* [Container With Most Water](https://leetcode.com/problems/container-with-most-water/)
## Binary
#### Study Links
- [Bits, Bytes, Building With Binary](https://medium.com/basecs/bits-bytes-building-with-binary-13cb4289aafa)
* [Bits, Bytes, Building With Binary](https://medium.com/basecs/bits-bytes-building-with-binary-13cb4289aafa)
#### Notes
@ -123,30 +122,30 @@ Questions involving binary representations and bitwise operations are asked some
Some helpful utility snippets:
- Test k<sup>th</sup> bit is set: `num & (1 << k) != 0`.
- Set k<sup>th</sup> bit: `num |= (1 << k)`.
- Turn off k<sup>th</sup> bit: `num &= ~(1 << k)`.
- Toggle the k<sup>th</sup> bit: `num ^= (1 << k)`.
- To check if a number is a power of 2, `num & num - 1 == 0`.
* Test k<sup>th</sup> bit is set: `num & (1 << k) != 0`.
* Set k<sup>th</sup> bit: `num |= (1 << k)`.
* Turn off k<sup>th</sup> bit: `num &= ~(1 << k)`.
* Toggle the k<sup>th</sup> bit: `num ^= (1 << k)`.
* To check if a number is a power of 2, `num & num - 1 == 0`.
#### Corner Cases
- Check for overflow/underflow.
- Negative numbers.
* Check for overflow/underflow.
* Negative numbers.
#### Practice Questions
- [Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/)
- [Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/)
- [Counting Bits](https://leetcode.com/problems/counting-bits/)
- [Missing Number](https://leetcode.com/problems/missing-number/)
- [Reverse Bits](https://leetcode.com/problems/reverse-bits/)
* [Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/)
* [Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/)
* [Counting Bits](https://leetcode.com/problems/counting-bits/)
* [Missing Number](https://leetcode.com/problems/missing-number/)
* [Reverse Bits](https://leetcode.com/problems/reverse-bits/)
## Dynamic Programming
#### Study Links
- [Demystifying Dynamic Programming](https://medium.freecodecamp.org/demystifying-dynamic-programming-3efafb8d4296)
* [Demystifying Dynamic Programming](https://medium.freecodecamp.org/demystifying-dynamic-programming-3efafb8d4296)
#### Notes
@ -156,17 +155,17 @@ Sometimes you do not need to store the whole DP table in memory, the last two va
#### Practice Questions
- 0/1 Knapsack
- [Climbing Stairs](https://leetcode.com/problems/climbing-stairs/)
- [Coin Change](https://leetcode.com/problems/coin-change/)
- [Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/)
- [Longest Common Subsequence]()
- [Word Break Problem](https://leetcode.com/problems/word-break/)
- [Combination Sum](https://leetcode.com/problems/combination-sum-iv/)
- [House Robber](https://leetcode.com/problems/house-robber/) and [House Robber II](https://leetcode.com/problems/house-robber-ii/)
- [Decode Ways](https://leetcode.com/problems/decode-ways/)
- [Unique Paths](https://leetcode.com/problems/unique-paths/)
- [Jump Game](https://leetcode.com/problems/jump-game/)
* 0/1 Knapsack
* [Climbing Stairs](https://leetcode.com/problems/climbing-stairs/)
* [Coin Change](https://leetcode.com/problems/coin-change/)
* [Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/)
* [Longest Common Subsequence]()
* [Word Break Problem](https://leetcode.com/problems/word-break/)
* [Combination Sum](https://leetcode.com/problems/combination-sum-iv/)
* [House Robber](https://leetcode.com/problems/house-robber/) and [House Robber II](https://leetcode.com/problems/house-robber-ii/)
* [Decode Ways](https://leetcode.com/problems/decode-ways/)
* [Unique Paths](https://leetcode.com/problems/unique-paths/)
* [Jump Game](https://leetcode.com/problems/jump-game/)
## Geometry
@ -180,26 +179,27 @@ To find out if two circles overlap, check that the distance between the two cent
#### Study Links
- [From Theory To Practice: Representing Graphs](https://medium.com/basecs/from-theory-to-practice-representing-graphs-cfd782c5be38)
- [Deep Dive Through A Graph: DFS Traversal](https://medium.com/basecs/deep-dive-through-a-graph-dfs-traversal-8177df5d0f13)
- [Going Broad In A Graph: BFS Traversal](https://medium.com/basecs/going-broad-in-a-graph-bfs-traversal-959bd1a09255)
* [From Theory To Practice: Representing Graphs](https://medium.com/basecs/from-theory-to-practice-representing-graphs-cfd782c5be38)
* [Deep Dive Through A Graph: DFS Traversal](https://medium.com/basecs/deep-dive-through-a-graph-dfs-traversal-8177df5d0f13)
* [Going Broad In A Graph: BFS Traversal](https://medium.com/basecs/going-broad-in-a-graph-bfs-traversal-959bd1a09255)
#### Notes
Be familiar with the various graph representations, graph search algorithms and their time and space complexities.
You can be given a list of edges and tasked to build your own graph from the edges to perform a traversal on. The common graph representations are:
- Adjacency matrix.
- Adjacency list.
- Hashmap of hashmaps.
* Adjacency matrix.
* Adjacency list.
* Hashmap of hashmaps.
A tree-like diagram could very well be a graph that allows for cycles and a naive recursive solution would not work. In that case you will have to handle cycles and keep a set of visited nodes when traversing.
#### Graph search algorithms:
- **Common** - Breadth-first Search, Depth-first Search
- **Uncommon** - Topological Sort, Dijkstra's algorithm
- **Rare** - Bellman-Ford algorithm, Floyd-Warshall algorithm, Prim's algorithm, Kruskal's algorithm
* **Common** - Breadth-first Search, Depth-first Search
* **Uncommon** - Topological Sort, Dijkstra's algorithm
* **Rare** - Bellman-Ford algorithm, Floyd-Warshall algorithm, Prim's algorithm, Kruskal's algorithm
In coding interviews, graphs are commonly represented as 2-D matrices where cells are the nodes and each cell can traverse to its adjacent cells (up/down/left/right). Hence it is important that you be familiar with traversing a 2-D matrix. When recursively traversing the matrix, always ensure that your next position is within the boundary of the matrix. More tips for doing depth-first searches on a matrix can be found [here](https://discuss.leetcode.com/topic/66065/python-dfs-bests-85-tips-for-all-dfs-in-matrix-question/). A simple template for doing depth-first searches on a matrix goes like this:
@ -226,21 +226,21 @@ def traverse(matrix):
#### Corner Cases
- Empty graph.
- Graph with one or two nodes.
- Disjoint graphs.
- Graph with cycles.
* Empty graph.
* Graph with one or two nodes.
* Disjoint graphs.
* Graph with cycles.
#### Practice Questions
- [Clone Graph](https://leetcode.com/problems/clone-graph/)
- [Course Schedule](https://leetcode.com/problems/course-schedule/)
- [Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow/)
- [Number of Islands](https://leetcode.com/problems/number-of-islands/)
- [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/)
- [Alien Dictionary (Leetcode Premium)](https://leetcode.com/problems/alien-dictionary/)
- [Graph Valid Tree (Leetcode Premium)](https://leetcode.com/problems/graph-valid-tree/)
- [Number of Connected Components in an Undirected Graph (Leetcode Premium)](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/)
* [Clone Graph](https://leetcode.com/problems/clone-graph/)
* [Course Schedule](https://leetcode.com/problems/course-schedule/)
* [Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow/)
* [Number of Islands](https://leetcode.com/problems/number-of-islands/)
* [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/)
* [Alien Dictionary (Leetcode Premium)](https://leetcode.com/problems/alien-dictionary/)
* [Graph Valid Tree (Leetcode Premium)](https://leetcode.com/problems/graph-valid-tree/)
* [Number of Connected Components in an Undirected Graph (Leetcode Premium)](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/)
## Interval
@ -268,17 +268,17 @@ def merge_overlapping_intervals(a, b):
#### Corner Cases
- Single interval.
- Non-overlapping intervals.
- An interval totally consumed within another interval.
- Duplicate intervals.
* Single interval.
* Non-overlapping intervals.
* An interval totally consumed within another interval.
* Duplicate intervals.
#### Practice Questions
- [Insert Interval](https://leetcode.com/problems/insert-interval/)
- [Merge Intervals](https://leetcode.com/problems/merge-intervals/)
- [Non-overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/)
- [Meeting Rooms (Leetcode Premium)](https://leetcode.com/problems/meeting-rooms/) and [Meeting Rooms II (Leetcode Premium)](https://leetcode.com/problems/meeting-rooms-ii/)
* [Insert Interval](https://leetcode.com/problems/insert-interval/)
* [Merge Intervals](https://leetcode.com/problems/merge-intervals/)
* [Non-overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/)
* [Meeting Rooms (Leetcode Premium)](https://leetcode.com/problems/meeting-rooms/) and [Meeting Rooms II (Leetcode Premium)](https://leetcode.com/problems/meeting-rooms-ii/)
## Linked List
@ -297,30 +297,32 @@ For partitioning linked lists, create two separate linked lists and join them ba
Linked lists problems share similarity with array problems, think about how you would do it for an array and try to apply it to a linked list.
Two pointer approaches are also common for linked lists. For example:
- Getting the k<sup>th</sup> from last node - Have two pointers, where one is k nodes ahead of the other. When the node ahead reaches the end, the other node is k nodes behind.
- Detecting cycles - Have two pointers, where one pointer increments twice as much as the other, if the two pointers meet, means that there is a cycle.
- Getting the middle node - Have two pointers, where one pointer increments twice as much as the other. When the faster node reaches the end of the list, the slower node will be at the middle.
* Getting the k<sup>th</sup> from last node - Have two pointers, where one is k nodes ahead of the other. When the node ahead reaches the end, the other node is k nodes behind.
* Detecting cycles - Have two pointers, where one pointer increments twice as much as the other, if the two pointers meet, means that there is a cycle.
* Getting the middle node - Have two pointers, where one pointer increments twice as much as the other. When the faster node reaches the end of the list, the slower node will be at the middle.
Be familiar with the following routines because many linked list questions make use of one or more of these routines in the solution:
- Counting the number of nodes in the linked list.
- Reversing a linked list in-place.
- Finding the middle node of the linked list using fast/slow pointers.
- Merging two lists together.
* Counting the number of nodes in the linked list.
* Reversing a linked list in-place.
* Finding the middle node of the linked list using fast/slow pointers.
* Merging two lists together.
#### Corner Cases
- Single node.
- Two nodes.
- Linked list has cycle. Clarify with the interviewer whether there can be a cycle in the list. Usually the answer is no.
* Single node.
* Two nodes.
* Linked list has cycle. Clarify with the interviewer whether there can be a cycle in the list. Usually the answer is no.
#### Practice Questions
- [Reverse a Linked List](https://leetcode.com/problems/reverse-linked-list/)
- [Detect Cycle in a Linked List](https://leetcode.com/problems/linked-list-cycle/)
- [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)
- [Merge K Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/)
- [Remove Nth Node From End Of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)
- [Reorder List](https://leetcode.com/problems/reorder-list/)
* [Reverse a Linked List](https://leetcode.com/problems/reverse-linked-list/)
* [Detect Cycle in a Linked List](https://leetcode.com/problems/linked-list-cycle/)
* [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)
* [Merge K Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/)
* [Remove Nth Node From End Of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)
* [Reorder List](https://leetcode.com/problems/reorder-list/)
## Math
@ -338,16 +340,16 @@ If the question asks to implement an operator such as power, squareroot or divis
#### Some common formulas:
- Sum of 1 to N = (n+1) * n/2
- Sum of GP = 2<sup>0</sup> + 2<sup>1</sup> + 2<sup>2</sup> + 2<sup>3</sup> + ... 2<sup>n</sup> = 2<sup>n+1</sup> - 1
- Permutations of N = N! / (N-K)!
- Combinations of N = N! / (K! * (N-K)!)
* Sum of 1 to N = (n+1) \* n/2
* Sum of GP = 2<sup>0</sup> + 2<sup>1</sup> + 2<sup>2</sup> + 2<sup>3</sup> + ... 2<sup>n</sup> = 2<sup>n+1</sup> - 1
* Permutations of N = N! / (N-K)!
* Combinations of N = N! / (K! \* (N-K)!)
#### Practice Questions
- [Pow(x, n)](https://leetcode.com/problems/powx-n/)
- [Sqrt(x)](https://leetcode.com/problems/sqrtx/)
- [Integer to English Words](https://leetcode.com/problems/integer-to-english-words/)
* [Pow(x, n)](https://leetcode.com/problems/powx-n/)
* [Sqrt(x)](https://leetcode.com/problems/sqrtx/)
* [Integer to English Words](https://leetcode.com/problems/integer-to-english-words/)
## Matrix
@ -372,16 +374,16 @@ transposed_matrix = zip(*matrix)
#### Corner Cases
- Empty matrix. Check that none of the arrays are 0 length.
- 1 x 1 matrix.
- Matrix with only one row or column.
* Empty matrix. Check that none of the arrays are 0 length.
* 1 x 1 matrix.
* Matrix with only one row or column.
#### Practice Questions
- [Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/)
- [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/)
- [Rotate Image](https://leetcode.com/problems/rotate-image/)
- [Word Search](https://leetcode.com/problems/word-search/)
* [Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/)
* [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/)
* [Rotate Image](https://leetcode.com/problems/rotate-image/)
* [Word Search](https://leetcode.com/problems/word-search/)
## Recursion
@ -395,8 +397,8 @@ Recursion implicitly uses a stack. Hence all recursive approaches can be rewritt
#### Practice Questions
- [Subsets](https://leetcode.com/problems/subsets/) and [Subsets II](https://leetcode.com/problems/subsets-ii/)
- [Strobogrammatic Number II (Leetcode Premium)](https://leetcode.com/problems/strobogrammatic-number-ii/)
* [Subsets](https://leetcode.com/problems/subsets/) and [Subsets II](https://leetcode.com/problems/subsets-ii/)
* [Strobogrammatic Number II (Leetcode Premium)](https://leetcode.com/problems/strobogrammatic-number-ii/)
## String
@ -412,21 +414,21 @@ If you need to keep a counter of characters, a common mistake is to say that the
Common data structures for looking up strings efficiently are
- [Trie / Prefix Tree](https://en.wikipedia.org/wiki/Trie)
- [Suffix Tree](https://en.wikipedia.org/wiki/Suffix_tree)
* [Trie / Prefix Tree](https://en.wikipedia.org/wiki/Trie)
* [Suffix Tree](https://en.wikipedia.org/wiki/Suffix_tree)
Common string algorithms are
- [Rabin Karp](https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm) for efficient searching of substring using a rolling hash.
- [KMP](https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm) for efficient searching of substring.
* [Rabin Karp](https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm) for efficient searching of substring using a rolling hash.
* [KMP](https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm) for efficient searching of substring.
#### Corner Cases
- Strings with only one distinct character.
* Strings with only one distinct character.
#### Non-repeating Characters
- Use a 26-bit bitmask to indicate which lower case latin characters are inside the string.
* Use a 26-bit bitmask to indicate which lower case latin characters are inside the string.
```py
mask = 0
@ -442,44 +444,44 @@ An anagram is word switch or word play. It is the result of re-arranging the let
To determine if two strings are anagrams, there are a few plausible approaches:
- Sorting both strings should produce the same resulting string. This takes O(nlgn) time and O(lgn) space.
- If we map each character to a prime number and we multiply each mapped number together, anagrams should have the same multiple (prime factor decomposition). This takes O(n) time and O(1) space.
- Frequency counting of characters will help to determine if two strings are anagrams. This also takes O(n) time and O(1) space.
* Sorting both strings should produce the same resulting string. This takes O(nlgn) time and O(lgn) space.
* If we map each character to a prime number and we multiply each mapped number together, anagrams should have the same multiple (prime factor decomposition). This takes O(n) time and O(1) space.
* Frequency counting of characters will help to determine if two strings are anagrams. This also takes O(n) time and O(1) space.
### Palindrome
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward, such as *madam* or *racecar*.
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward, such as _madam_ or _racecar_.
Here are ways to determine if a string is a palindrome:
- Reverse the string and it should be equal to itself.
- Have two pointers at the start and end of the string. Move the pointers inward till they meet. At any point in time, the characters at both pointers should match.
* Reverse the string and it should be equal to itself.
* Have two pointers at the start and end of the string. Move the pointers inward till they meet. At any point in time, the characters at both pointers should match.
The order of characters within the string matters, so HashMaps are usually not helpful.
When a question is about counting the number of palindromes, a common trick is to have two pointers that move outward, away from the middle. Note that palindromes can be even or odd length. For each middle pivot position, you need to check it twice: Once that includes the character and once without the character.
- For substrings, you can terminate early once there is no match.
- For subsequences, use dynamic programming as there are overlapping subproblems. Check out [this question](https://leetcode.com/problems/longest-palindromic-subsequence/).
* For substrings, you can terminate early once there is no match.
* For subsequences, use dynamic programming as there are overlapping subproblems. Check out [this question](https://leetcode.com/problems/longest-palindromic-subsequence/).
#### Practice Questions
- [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/)
- [Longest Repeating Character Replacement](https://leetcode.com/problems/longest-repeating-character-replacement/)
- [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/description/)
- [Valid Anagram](https://leetcode.com/problems/valid-anagram)
- [Group Anagrams](https://leetcode.com/problems/group-anagrams/)
- [Valid Parentheses](https://leetcode.com/problems/valid-parentheses)
- [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/)
- [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/)
- [Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/)
- [Encode and Decode Strings (Leetcode Premium)](https://leetcode.com/problems/encode-and-decode-strings/)
* [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/)
* [Longest Repeating Character Replacement](https://leetcode.com/problems/longest-repeating-character-replacement/)
* [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/description/)
* [Valid Anagram](https://leetcode.com/problems/valid-anagram)
* [Group Anagrams](https://leetcode.com/problems/group-anagrams/)
* [Valid Parentheses](https://leetcode.com/problems/valid-parentheses)
* [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/)
* [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/)
* [Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/)
* [Encode and Decode Strings (Leetcode Premium)](https://leetcode.com/problems/encode-and-decode-strings/)
## Tree
#### Study Links
- [Leaf It Up To Binary Trees](https://medium.com/basecs/leaf-it-up-to-binary-trees-11001aaf746d)
* [Leaf It Up To Binary Trees](https://medium.com/basecs/leaf-it-up-to-binary-trees-11001aaf746d)
#### Notes
@ -497,13 +499,12 @@ If the question involves summation of nodes along the way, be sure to check whet
You should be very familiar with writing pre-order, in-order, and post-order traversal recursively. As an extension, challenge yourself by writing them iteratively. Sometimes interviewers ask candidates for the iterative approach, especially if the candidate finishes writing the recursive approach too quickly.
#### Corner Cases
- Empty tree.
- Single node.
- Two nodes.
- Very skewed tree (like a linked list).
* Empty tree.
* Single node.
* Two nodes.
* Very skewed tree (like a linked list).
### Binary Tree
@ -519,24 +520,24 @@ When a question involves a BST, the interviewer is usually looking for a solutio
#### Practice Questions
- [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/)
- [Same Tree](https://leetcode.com/problems/same-tree/)
- [Invert/Flip Binary Tree](https://leetcode.com/problems/invert-binary-tree/)
- [Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/)
- [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/)
- [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/)
- [Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/)
- [Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/)
- [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)
- [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/)
- [Lowest Common Ancestor of BST](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/)
* [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/)
* [Same Tree](https://leetcode.com/problems/same-tree/)
* [Invert/Flip Binary Tree](https://leetcode.com/problems/invert-binary-tree/)
* [Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/)
* [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/)
* [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/)
* [Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/)
* [Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/)
* [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)
* [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/)
* [Lowest Common Ancestor of BST](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/)
## Trie
#### Study Links
- [Trying to Understand Tries](https://medium.com/basecs/trying-to-understand-tries-3ec6bede0014)
- [Implement Trie (Prefix Tree)](https://leetcode.com/articles/implement-trie-prefix-tree/)
* [Trying to Understand Tries](https://medium.com/basecs/trying-to-understand-tries-3ec6bede0014)
* [Implement Trie (Prefix Tree)](https://leetcode.com/articles/implement-trie-prefix-tree/)
#### Notes
@ -548,31 +549,31 @@ Be familiar with implementing, from scratch, a `Trie` class and its `add`, `remo
#### Practice Questions
- [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree)
- [Add and Search Word](https://leetcode.com/problems/add-and-search-word-data-structure-design)
- [Word Search II](https://leetcode.com/problems/word-search-ii/)
* [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree)
* [Add and Search Word](https://leetcode.com/problems/add-and-search-word-data-structure-design)
* [Word Search II](https://leetcode.com/problems/word-search-ii/)
## Heap
#### Study Links
- [Learning to Love Heaps](https://medium.com/basecs/learning-to-love-heaps-cef2b273a238)
* [Learning to Love Heaps](https://medium.com/basecs/learning-to-love-heaps-cef2b273a238)
#### Notes
If you see a top or lowest *k* being mentioned in the question, it is usually a signal that a heap can be used to solve the problem, such as in [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/).
If you see a top or lowest _k_ being mentioned in the question, it is usually a signal that a heap can be used to solve the problem, such as in [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/).
If you require the top *k* elements use a Min Heap of size *k*. Iterate through each element, pushing it into the heap. Whenever the heap size exceeds *k*, remove the minimum element, that will guarantee that you have the *k* largest elements.
If you require the top _k_ elements use a Min Heap of size _k_. Iterate through each element, pushing it into the heap. Whenever the heap size exceeds _k_, remove the minimum element, that will guarantee that you have the _k_ largest elements.
#### Practice Questions
- [Merge K Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/)
- [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/)
- [Find Median from Data Stream](https://leetcode.com/problems/find-median-from-data-stream/)
* [Merge K Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/)
* [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/)
* [Find Median from Data Stream](https://leetcode.com/problems/find-median-from-data-stream/)
###### References
- http://blog.triplebyte.com/how-to-pass-a-programming-interview
- https://quip.com/q41AA3OmoZbC
- http://www.geeksforgeeks.org/must-do-coding-questions-for-companies-like-amazon-microsoft-adobe/
- https://medium.com/basecs
* http://blog.triplebyte.com/how-to-pass-a-programming-interview
* https://quip.com/q41AA3OmoZbC
* http://www.geeksforgeeks.org/must-do-coding-questions-for-companies-like-amazon-microsoft-adobe/
* https://medium.com/basecs

@ -1,14 +1,13 @@
Arrays
==
# Arrays
- In an array of arrays, e.g. given `[[], [1, 2, 3], [4, 5], [], [], [6, 7], [8], [9, 10], [], []]`, print: `1, 2, 3, 4, 5, 6, 7, 8, 9, 10`.
- Implement an iterator that supports `hasNext()`, `next()` and `remove()` methods.
- Given a list of item prices, find all possible combinations of items that sum a particular value `K`.
- Paginate an array with constraints, such as skipping certain items.
- Implement a circular buffer using an array.
- Given array of arrays, sort them in ascending order.
- Given an array of integers, print out a histogram using the said array; include a base layer (all stars)
- E.g. `[5, 4, 0, 3, 4, 1]`
* In an array of arrays, e.g. given `[[], [1, 2, 3], [4, 5], [], [], [6, 7], [8], [9, 10], [], []]`, print: `1, 2, 3, 4, 5, 6, 7, 8, 9, 10`.
* Implement an iterator that supports `hasNext()`, `next()` and `remove()` methods.
* Given a list of item prices, find all possible combinations of items that sum a particular value `K`.
* Paginate an array with constraints, such as skipping certain items.
* Implement a circular buffer using an array.
* Given array of arrays, sort them in ascending order.
* Given an array of integers, print out a histogram using the said array; include a base layer (all stars)
* E.g. `[5, 4, 0, 3, 4, 1]`
```
*
@ -19,42 +18,42 @@ Arrays
******
```
- Given an array and an index, find the product of the elements of the array except the element at that index.
- Given a set of rectangles represented by a height and an interval along the y-axis, determine the size of its union.
- Given 2 separate arrays, write a method to find the values that exist in both arrays and return them.
- Given an array of integers find whether there is a sub-sequence that sums to 0 and return it.
- E.g. `[1, 2, -3, 1]` => `[1, 2, -3]` or `[2, -3, 1]`.
- Given an input array and another array that describes a new index for each element, mutate the input array so that each element ends up in their new index. Discuss the runtime of the algorithm and how you can be sure there would not be any infinite loops.
- Given an array of non-negative numbers, find continuous subarray with sum to S.
- [Source](http://blog.gainlo.co/index.php/2016/06/01/subarray-with-given-sum/).
- Given an array of numbers list out all triplets that sum to 0. Do so with a running time of less than O(n^3).
- [Source](http://blog.gainlo.co/index.php/2016/07/19/3sum/).
- Given an array of numbers list out all quadruplets that sum to 0. Do so with a running time of less than O(n^4).
- Given an array of integers, move all the zeroes to the end while preserving the order of the other elements. You have to do it in-place and are not allowed to use any extra storage.
- Given an array of integers, find the subarray with the largest sum. Can you do it in linear time.
- Maximum subarray sum problem.
- You have an array with the heights of an island (at point 1, point 2 etc) and you want to know how much water would remain on this island (without flowing away).
- Trapping rain water question.
- Given an array containing only digits `0-9`, add one to the number and return the array.
- E.g. Given `[1, 4, 2, 1]` which represents `1421`, return `[1, 4, 2, 2]` which represents `1422`.
- Find the second maximum value in an array.
- Given an array, find the longest arithmetic progression.
- Rotate an array by an offset of k.
- Remove duplicates in an unsorted array where the duplicates are at a distance of k or less from each other.
- Given an unsorted list of integers, return true if the list contains any duplicates within k indices of each element. Do it faster than O(n^2).
- Given an unsorted list of integers, return true if the list contains any fuzzy duplicates within k indices of each element. A fuzzy duplicate is another integer within d of the original integer. Do it faster than O(n^2).
- E.g. If d = 4, then 6 is a fuzzy duplicate of 3 but 8 is not.
- Say you have an unordered list of numbers ranging from 1 to n, and one of the numbers is removed, how do you find that number? What if two numbers are removed?
- Given an array of string, find the duplicated elements.
- [Source](http://blog.gainlo.co/index.php/2016/05/10/duplicate-elements-of-an-array/).
- Given an array of integers, find a maximum sum of non-adjacent elements.
- E.g. `[1, 0, 3, 9, 2]` should return `10 (1 + 9)`.
- [Source](http://blog.gainlo.co/index.php/2016/12/02/uber-interview-question-maximum-sum-non-adjacent-elements/)
- Given an array of integers, modify the array by moving all the zeros to the end (right side). The order of other elements doesn't matter.
- E.g. `[1, 2, 0, 3, 0, 1, 2]`, the program can output `[1, 2, 3, 1, 2, 0, 0]`.
- [Source](http://blog.gainlo.co/index.php/2016/11/18/uber-interview-question-move-zeroes/).
- Given an array, return the length of the longest increasing contiguous subarray.
- E.g., `[1, 3, 2, 3, 4, 8, 7, 9]`, should return `4` because the longest increasing array is `[2, 3, 4, 8]`.
- [Source](http://blog.gainlo.co/index.php/2017/02/02/uber-interview-questions-longest-increasing-subarray/).
- Given an array of integers where every value appears twice except one, find the single, non-repeating value. Follow up: do so with O(1) space.
- E.g., `[2, 5, 3, 2, 1, 3, 4, 5, 1]` returns 4, because it is the only value that appears in the array only once.
* Given an array and an index, find the product of the elements of the array except the element at that index.
* Given a set of rectangles represented by a height and an interval along the y-axis, determine the size of its union.
* Given 2 separate arrays, write a method to find the values that exist in both arrays and return them.
* Given an array of integers find whether there is a sub-sequence that sums to 0 and return it.
* E.g. `[1, 2, -3, 1]` => `[1, 2, -3]` or `[2, -3, 1]`.
* Given an input array and another array that describes a new index for each element, mutate the input array so that each element ends up in their new index. Discuss the runtime of the algorithm and how you can be sure there would not be any infinite loops.
* Given an array of non-negative numbers, find continuous subarray with sum to S.
* [Source](http://blog.gainlo.co/index.php/2016/06/01/subarray-with-given-sum/).
* Given an array of numbers list out all triplets that sum to 0. Do so with a running time of less than O(n^3).
* [Source](http://blog.gainlo.co/index.php/2016/07/19/3sum/).
* Given an array of numbers list out all quadruplets that sum to 0. Do so with a running time of less than O(n^4).
* Given an array of integers, move all the zeroes to the end while preserving the order of the other elements. You have to do it in-place and are not allowed to use any extra storage.
* Given an array of integers, find the subarray with the largest sum. Can you do it in linear time.
* Maximum subarray sum problem.
* You have an array with the heights of an island (at point 1, point 2 etc) and you want to know how much water would remain on this island (without flowing away).
* Trapping rain water question.
* Given an array containing only digits `0-9`, add one to the number and return the array.
* E.g. Given `[1, 4, 2, 1]` which represents `1421`, return `[1, 4, 2, 2]` which represents `1422`.
* Find the second maximum value in an array.
* Given an array, find the longest arithmetic progression.
* Rotate an array by an offset of k.
* Remove duplicates in an unsorted array where the duplicates are at a distance of k or less from each other.
* Given an unsorted list of integers, return true if the list contains any duplicates within k indices of each element. Do it faster than O(n^2).
* Given an unsorted list of integers, return true if the list contains any fuzzy duplicates within k indices of each element. A fuzzy duplicate is another integer within d of the original integer. Do it faster than O(n^2).
* E.g. If d = 4, then 6 is a fuzzy duplicate of 3 but 8 is not.
* Say you have an unordered list of numbers ranging from 1 to n, and one of the numbers is removed, how do you find that number? What if two numbers are removed?
* Given an array of string, find the duplicated elements.
* [Source](http://blog.gainlo.co/index.php/2016/05/10/duplicate-elements-of-an-array/).
* Given an array of integers, find a maximum sum of non-adjacent elements.
* E.g. `[1, 0, 3, 9, 2]` should return `10 (1 + 9)`.
* [Source](http://blog.gainlo.co/index.php/2016/12/02/uber-interview-question-maximum-sum-non-adjacent-elements/)
* Given an array of integers, modify the array by moving all the zeros to the end (right side). The order of other elements doesn't matter.
* E.g. `[1, 2, 0, 3, 0, 1, 2]`, the program can output `[1, 2, 3, 1, 2, 0, 0]`.
* [Source](http://blog.gainlo.co/index.php/2016/11/18/uber-interview-question-move-zeroes/).
* Given an array, return the length of the longest increasing contiguous subarray.
* E.g., `[1, 3, 2, 3, 4, 8, 7, 9]`, should return `4` because the longest increasing array is `[2, 3, 4, 8]`.
* [Source](http://blog.gainlo.co/index.php/2017/02/02/uber-interview-questions-longest-increasing-subarray/).
* Given an array of integers where every value appears twice except one, find the single, non-repeating value. Follow up: do so with O(1) space.
* E.g., `[2, 5, 3, 2, 1, 3, 4, 5, 1]` returns 4, because it is the only value that appears in the array only once.

@ -1,7 +1,6 @@
Bit Manipulation
==
# Bit Manipulation
- How do you verify if an interger is a power of 2?
- Write a program to print the binary representation of an integer.
- Write a program to print out the number of 1 bits in a given integer.
- Write a program to determine the largest possible integer using the same number of 1 bits in a given number.
* How do you verify if an interger is a power of 2?
* Write a program to print the binary representation of an integer.
* Write a program to print out the number of 1 bits in a given integer.
* Write a program to determine the largest possible integer using the same number of 1 bits in a given number.

@ -1,14 +1,15 @@
Dynamic Programming
==
# Dynamic Programming
- Given a flight itinerary consisting of starting city, destination city, and ticket price (2D list) - find the optimal price flight path to get from start to destination. (A variation of Dynamic Programming Shortest Path)
- Given some coin denominations and a target value `M`, return the coins combination with the minimum number of coins.
- Time complexity: `O(MN)`, where N is the number of distinct type of coins.
- Space complexity: `O(M)`.
- Given a set of numbers in an array which represent a number of consecutive days of Airbnb reservation requested, as a host, pick the sequence which maximizes the number of days of occupancy, at the same time, leaving at least a 1-day gap in-between bookings for cleaning.
- The problem reduces to finding the maximum sum of non-consecutive array elements.
- E.g.
~~~
* Given a flight itinerary consisting of starting city, destination city, and ticket price (2D list) - find the optimal price flight path to get from start to destination. (A variation of Dynamic Programming Shortest Path)
* Given some coin denominations and a target value `M`, return the coins combination with the minimum number of coins.
* Time complexity: `O(MN)`, where N is the number of distinct type of coins.
* Space complexity: `O(M)`.
* Given a set of numbers in an array which represent a number of consecutive days of Airbnb reservation requested, as a host, pick the sequence which maximizes the number of days of occupancy, at the same time, leaving at least a 1-day gap in-between bookings for cleaning.
* The problem reduces to finding the maximum sum of non-consecutive array elements.
* E.g.
```
// [5, 1, 1, 5] => 10
The above array would represent an example booking period as follows -
// Dec 1 - 5
@ -22,5 +23,6 @@ Dynamic Programming
Similarly,
// [3, 6, 4] => 7
// [4, 10, 3, 1, 5] => 15
~~~
- Given a list of denominations (e.g., `[1, 2, 5]` means you have coins worth $1, $2, and $5) and a target number `k`, find all possible combinations, if any, of coins in the given denominations that add up to `k`. You can use coins of the same denomination more than once.
```
* Given a list of denominations (e.g., `[1, 2, 5]` means you have coins worth $1, $2, and $5) and a target number `k`, find all possible combinations, if any, of coins in the given denominations that add up to `k`. You can use coins of the same denomination more than once.

@ -1,7 +1,6 @@
Geometry
==
# Geometry
- You have a plane with lots of rectangles on it, find out how many of them intersect.
- Which data structure would you use to query the k-nearest points of a set on a 2D plane?
- Given many points, find k points that are closest to the origin.
- How would you triangulate a polygon?
* You have a plane with lots of rectangles on it, find out how many of them intersect.
* Which data structure would you use to query the k-nearest points of a set on a 2D plane?
* Given many points, find k points that are closest to the origin.
* How would you triangulate a polygon?

@ -1,10 +1,9 @@
Graph
==
# Graph
- Given a list of sorted words from an alien dictionary, find the order of the alphabet.
- Alien Dictionary Topological Sort question.
- Find if a given string matches any path in a labeled graph. A path may contain cycles.
- Given a bipartite graph, separate the vertices into two sets.
- 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.
- Given a graph and two nodes, determine if there exists a path between them.
- Determine if a cycle exists in the graph.
* Given a list of sorted words from an alien dictionary, find the order of the alphabet.
* Alien Dictionary Topological Sort question.
* Find if a given string matches any path in a labeled graph. A path may contain cycles.
* Given a bipartite graph, separate the vertices into two sets.
* 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.
* Given a graph and two nodes, determine if there exists a path between them.
* Determine if a cycle exists in the graph.

@ -1,7 +1,6 @@
Hash Table
==
# Hash Table
- Describe an implementation of a least-used cache, and big-O notation of it.
- A question involving an API's integration with hash map where the buckets of hash map are made up of linked lists.
- 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()`.
- [Source](http://blog.gainlo.co/index.php/2016/08/14/uber-interview-question-map-implementation/).
* Describe an implementation of a least-used cache, and big-O notation of it.
* A question involving an API's integration with hash map where the buckets of hash map are made up of linked lists.
* 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()`.
* [Source](http://blog.gainlo.co/index.php/2016/08/14/uber-interview-question-map-implementation/).

@ -1,5 +1,4 @@
Heap
==
# Heap
- Merge `K` sorted lists together into a single list.
- Given a stream of integers, write an efficient function that returns the median value of the integers.
* Merge `K` sorted lists together into a single list.
* Given a stream of integers, write an efficient function that returns the median value of the integers.

@ -1,7 +1,7 @@
Interval
==
# Interval
* Given a list of schedules, provide a list of times that are available for a meeting.
- Given a list of schedules, provide a list of times that are available for a meeting.
```
[
[[4,5], [6,10], [12,14]],
@ -12,17 +12,17 @@ Interval
Example Output:
[[0,4], [11,12], [16,23]]
```
- You have a number of meetings (with their start and end times). You need to schedule them using the minimum number of rooms. Return the list of meetings in every room.
- Interval ranges:
- Given 2 interval ranges, create a function to tell me if these ranges intersect. Both start and end are inclusive: `[start, end]`
- E.g. `[1, 4]` and `[5, 6]` => `false`
- E.g. `[1, 4]` and `[3, 6]` => `true`
- Given 2 interval ranges that intersect, now create a function to merge the 2 ranges into a single continuous range.
- E.g. `[1, 4]` and `[3, 6]` => `[1, 6]`
- Now create a function that takes a group of unsorted, unorganized intervals, merge any intervals that intersect and sort them. The result should be a group of sorted, non-intersecting intervals.
- Now create a function to merge a new interval into a group of sorted, non-intersecting intervals. After the merge, all intervals should remain
non-intersecting.
- Given a list of meeting times, check if any of them overlap. The follow-up question is to return the minimum number of rooms required to accommodate all the meetings.
- [Source](http://blog.gainlo.co/index.php/2016/07/12/meeting-room-scheduling-problem/)
- If you have a list of intervals, how would you merge them?
- E.g. `[1, 3], [8, 11], [2, 6]` => `[1, 6], [8-11]`
* You have a number of meetings (with their start and end times). You need to schedule them using the minimum number of rooms. Return the list of meetings in every room.
* Interval ranges:
* Given 2 interval ranges, create a function to tell me if these ranges intersect. Both start and end are inclusive: `[start, end]`
* E.g. `[1, 4]` and `[5, 6]` => `false`
* E.g. `[1, 4]` and `[3, 6]` => `true`
* Given 2 interval ranges that intersect, now create a function to merge the 2 ranges into a single continuous range.
* E.g. `[1, 4]` and `[3, 6]` => `[1, 6]`
* Now create a function that takes a group of unsorted, unorganized intervals, merge any intervals that intersect and sort them. The result should be a group of sorted, non-intersecting intervals.
* Now create a function to merge a new interval into a group of sorted, non-intersecting intervals. After the merge, all intervals should remain non-intersecting.
* Given a list of meeting times, check if any of them overlap. The follow-up question is to return the minimum number of rooms required to accommodate all the meetings.
* [Source](http://blog.gainlo.co/index.php/2016/07/12/meeting-room-scheduling-problem/)
* If you have a list of intervals, how would you merge them?
* E.g. `[1, 3], [8, 11], [2, 6]` => `[1, 6], [8-11]`

@ -1,12 +1,11 @@
Linked List
==
# Linked List
- 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.
- [Source](http://blog.gainlo.co/index.php/2016/06/12/flatten-a-linked-list/)
- Reverse a singly linked list. Implement it recursively and iteratively.
- Convert a binary tree to a doubly circular linked list.
- Implement an LRU cache with O(1) runtime for all its operations.
- Check distance between values in linked list.
- A question involving an API's integration with hash map where the buckets of hash map are made up of linked lists.
- 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.
- How can you tell if a Linked List is a Palindrome?
* 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.
* [Source](http://blog.gainlo.co/index.php/2016/06/12/flatten-a-linked-list/)
* Reverse a singly linked list. Implement it recursively and iteratively.
* Convert a binary tree to a doubly circular linked list.
* Implement an LRU cache with O(1) runtime for all its operations.
* Check distance between values in linked list.
* A question involving an API's integration with hash map where the buckets of hash map are made up of linked lists.
* 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.
* How can you tell if a Linked List is a Palindrome?

@ -1,20 +1,19 @@
Math
==
# Math
- Create a square root function.
- Given a string such as "123" or "67", write a function to output the number represented by the string without using casting.
- Make a program that can print out the text form of numbers from 1 - 1000 (ex. 20 is "twenty", 105 is "one hundred and five").
- Write a function that parses Roman numerals.
- E.g. `XIV` returns `14`.
- Write in words for a given digit.
- E.g. `123` returns `one hundred and twenty three`.
- Given a number `N`, find the largest number just smaller than `N` that can be formed using the same digits as `N`.
- Compute the square root of `N` without using any existing functions.
- Given numbers represented as binary strings, and return the string containing their sum.
- E.g. `add('10010', '101')` returns `'10111'`.
- Take in an integer and return its english word-format.
- E.g. 1 -> "one", -10,203 -> "negative ten thousand two hundred and three".
- Write a function that returns values randomly, according to their weight. Suppose we have 3 elements with their weights: A (1), B (1) and C (2). The function should return A with probability 25%, B with 25% and C with 50% based on the weights.
- [Source](http://blog.gainlo.co/index.php/2016/11/11/uber-interview-question-weighted-random-numbers/)
- Given a number, how can you get the next greater number with the same set of digits?
- [Source](http://blog.gainlo.co/index.php/2017/01/20/arrange-given-numbers-to-form-the-biggest-number-possible/)
* Create a square root function.
* Given a string such as "123" or "67", write a function to output the number represented by the string without using casting.
* Make a program that can print out the text form of numbers from 1 - 1000 (ex. 20 is "twenty", 105 is "one hundred and five").
* Write a function that parses Roman numerals.
* E.g. `XIV` returns `14`.
* Write in words for a given digit.
* E.g. `123` returns `one hundred and twenty three`.
* Given a number `N`, find the largest number just smaller than `N` that can be formed using the same digits as `N`.
* Compute the square root of `N` without using any existing functions.
* Given numbers represented as binary strings, and return the string containing their sum.
* E.g. `add('10010', '101')` returns `'10111'`.
* Take in an integer and return its english word-format.
* E.g. 1 -> "one", -10,203 -> "negative ten thousand two hundred and three".
* Write a function that returns values randomly, according to their weight. Suppose we have 3 elements with their weights: A (1), B (1) and C (2). The function should return A with probability 25%, B with 25% and C with 50% based on the weights.
* [Source](http://blog.gainlo.co/index.php/2016/11/11/uber-interview-question-weighted-random-numbers/)
* Given a number, how can you get the next greater number with the same set of digits?
* [Source](http://blog.gainlo.co/index.php/2017/01/20/arrange-given-numbers-to-form-the-biggest-number-possible/)

@ -1,18 +1,17 @@
Matrix
==
# Matrix
- You're given a 3 x 3 board of a tile puzzle, with 8 tiles numbered 1 to 8, and an empty spot. You can move any tile adjacent to the empty spot, to the empty spot, creating an empty spot where the tile originally was. The goal is to find a series of moves that will solve the board, i.e. get `[[1, 2, 3], [4, 5, 6], [7, 8, - ]]` where - is the empty tile.
- Boggle implementation. Given a dictionary, and a matrix of letters, find all the words in the matrix that are in the dictionary. You can go across, down or diagonally.
- The values of the matrix will represent numbers of carrots available to the rabbit in each square of the garden. If the garden does not have an exact center, the rabbit should start in the square closest to the center with the highest carrot count. On a given turn, the rabbit will eat the carrots available on the square that it is on, and then move up, down, left, or right, choosing the square that has the most carrots. If there are no carrots left on any of the adjacent squares, the rabbit will go to sleep. You may assume that the rabbit will never have to choose between two squares with the same number of carrots. Write a function which takes a garden matrix and returns the number of carrots the rabbit eats. You may assume the matrix is rectangular with at least 1 row and 1 column, and that it is populated with non-negative integers. For example,
- Example: `[[5, 7, 8, 6, 3], [0, 0, 7, 0, 4], [4, 6, 3, 4, 9], [3, 1, 0, 5, 8]]` should return `27`.
- Print a matrix in a spiral fashion.
- In the Game of life, calculate how to compute the next state of the board. Follow up was to do it if there were memory constraints (board represented by a 1 TB file).
- Grid Illumination: Given an NxN grid with an array of lamp coordinates. Each lamp provides illumination to every square on their x axis, every square on their y axis, and every square that lies in their diagonal (think of a Queen in chess). Given an array of query coordinates, determine whether that point is illuminated or not. The catch is when checking a query all lamps adjacent to, or on, that query get turned off. The ranges for the variables/arrays were about: 10^3 < N < 10^9, 10^3 < lamps < 10^9, 10^3 < queries < 10^9.
- You are given a matrix of integers. Modify the matrix such that if a row or column contains a 0, make the values in the entire row or column 0.
- Given an N x N matrix filled randomly with different colors (no limit on what the colors are), find the total number of groups of each color - a group consists of adjacent cells of the same color touching each other.
- You have a 4 x 4 board with characters. You need to write a function that finds if a certain word exists in the board. You can only jump to neighboring characters (including diagonally adjacent).
- Count the number of islands in a binary matrix of 0's and 1's.
- Check a 6 x 7 Connect 4 board for a winning condition.
- Given a fully-filled Sudoku board, check whether fulfills the Sudoku condition.
- Implement a function that checks if a player has won tic-tac-toe.
- Given an N x N matrix of 1's and 0's, figure out if all of the 1's are connected.
* You're given a 3 x 3 board of a tile puzzle, with 8 tiles numbered 1 to 8, and an empty spot. You can move any tile adjacent to the empty spot, to the empty spot, creating an empty spot where the tile originally was. The goal is to find a series of moves that will solve the board, i.e. get `[[1, 2, 3], [4, 5, 6], [7, 8, - ]]` where - is the empty tile.
* Boggle implementation. Given a dictionary, and a matrix of letters, find all the words in the matrix that are in the dictionary. You can go across, down or diagonally.
* The values of the matrix will represent numbers of carrots available to the rabbit in each square of the garden. If the garden does not have an exact center, the rabbit should start in the square closest to the center with the highest carrot count. On a given turn, the rabbit will eat the carrots available on the square that it is on, and then move up, down, left, or right, choosing the square that has the most carrots. If there are no carrots left on any of the adjacent squares, the rabbit will go to sleep. You may assume that the rabbit will never have to choose between two squares with the same number of carrots. Write a function which takes a garden matrix and returns the number of carrots the rabbit eats. You may assume the matrix is rectangular with at least 1 row and 1 column, and that it is populated with non-negative integers. For example,
* Example: `[[5, 7, 8, 6, 3], [0, 0, 7, 0, 4], [4, 6, 3, 4, 9], [3, 1, 0, 5, 8]]` should return `27`.
* Print a matrix in a spiral fashion.
* In the Game of life, calculate how to compute the next state of the board. Follow up was to do it if there were memory constraints (board represented by a 1 TB file).
* Grid Illumination: Given an NxN grid with an array of lamp coordinates. Each lamp provides illumination to every square on their x axis, every square on their y axis, and every square that lies in their diagonal (think of a Queen in chess). Given an array of query coordinates, determine whether that point is illuminated or not. The catch is when checking a query all lamps adjacent to, or on, that query get turned off. The ranges for the variables/arrays were about: 10^3 < N < 10^9, 10^3 < lamps < 10^9, 10^3 < queries < 10^9.
* You are given a matrix of integers. Modify the matrix such that if a row or column contains a 0, make the values in the entire row or column 0.
* Given an N x N matrix filled randomly with different colors (no limit on what the colors are), find the total number of groups of each color - a group consists of adjacent cells of the same color touching each other.
* You have a 4 x 4 board with characters. You need to write a function that finds if a certain word exists in the board. You can only jump to neighboring characters (including diagonally adjacent).
* Count the number of islands in a binary matrix of 0's and 1's.
* Check a 6 x 7 Connect 4 board for a winning condition.
* Given a fully-filled Sudoku board, check whether fulfills the Sudoku condition.
* Implement a function that checks if a player has won tic-tac-toe.
* Given an N x N matrix of 1's and 0's, figure out if all of the 1's are connected.

@ -1,8 +1,7 @@
Object-Oriented Programming
==
# Object-Oriented Programming
- How would you design a chess game? What classes and objects would you use? What methods would they have?
- How would you design the data structures for a book keeping system for a library?
- Explain how you would design a HTTP server? Give examples of classes, methods, and interfaces. What are the challenges here?
- Discuss algorithms and data structures for a garbage collector?
- How would you implement an HR system to keep track of employee salaries and benefits?
* How would you design a chess game? What classes and objects would you use? What methods would they have?
* How would you design the data structures for a book keeping system for a library?
* Explain how you would design a HTTP server? Give examples of classes, methods, and interfaces. What are the challenges here?
* Discuss algorithms and data structures for a garbage collector?
* How would you implement an HR system to keep track of employee salaries and benefits?

@ -1,12 +1,11 @@
Permutation
==
# Permutation
- 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.
- Give all possible letter combinations from a phone number.
- Generate all subsets of a string.
- Print all possible `N` pairs of balanced parentheses.
- E.g. when `N` is `2`, the function should print `(())` and `()()`.
- E.g. when `N` is `3`, we should get `((()))`, `(()())`, `(())()`, `()(())`, `()()()`.
- [Source](http://blog.gainlo.co/index.php/2016/12/23/uber-interview-questions-permutations-parentheses/)
- Given a list of arrays, return a list of arrays, where each array is a combination of one element in each given array.
- 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]]`.
* 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.
* Give all possible letter combinations from a phone number.
* Generate all subsets of a string.
* Print all possible `N` pairs of balanced parentheses.
* E.g. when `N` is `2`, the function should print `(())` and `()()`.
* E.g. when `N` is `3`, we should get `((()))`, `(()())`, `(())()`, `()(())`, `()()()`.
* [Source](http://blog.gainlo.co/index.php/2016/12/23/uber-interview-questions-permutations-parentheses/)
* Given a list of arrays, return a list of arrays, where each array is a combination of one element in each given array.
* 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]]`.

@ -1,5 +1,4 @@
Queue
==
# Queue
- Implement a Queue class from scratch with an existing bug, the bug is that it cannot take more than 5 elements.
- 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).
* Implement a Queue class from scratch with an existing bug, the bug is that it cannot take more than 5 elements.
* 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).

@ -1,16 +1,15 @@
Sorting and Searching
==
# Sorting and Searching
- Sorting search results on a page given a certain set of criteria.
- Sort a list of numbers in which each number is at a distance `K` from its actual position.
- Given an array of integers, sort the array so that all odd indexes are greater than the even indexes.
- 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).
- Search for an element in a sorted and rotated array.
- [Source](http://blog.gainlo.co/index.php/2017/01/12/rotated-array-binary-search/)
- Sort a list where each element is no more than k positions away from its sorted position.
- Search for an item in a sorted, but rotated, array.
- Merge two sorted lists together.
- Give 3 distinct algorithms to find the K largest values in a list of N items.
- Find the minimum element in a sorted rotated array in faster than O(n) time.
- Write a function that takes a number as input and outputs the biggest number with the same set of digits.
- [Source](http://blog.gainlo.co/index.php/2017/01/20/arrange-given-numbers-to-form-the-biggest-number-possible/)
* Sorting search results on a page given a certain set of criteria.
* Sort a list of numbers in which each number is at a distance `K` from its actual position.
* Given an array of integers, sort the array so that all odd indexes are greater than the even indexes.
* 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).
* Search for an element in a sorted and rotated array.
* [Source](http://blog.gainlo.co/index.php/2017/01/12/rotated-array-binary-search/)
* Sort a list where each element is no more than k positions away from its sorted position.
* Search for an item in a sorted, but rotated, array.
* Merge two sorted lists together.
* Give 3 distinct algorithms to find the K largest values in a list of N items.
* Find the minimum element in a sorted rotated array in faster than O(n) time.
* Write a function that takes a number as input and outputs the biggest number with the same set of digits.
* [Source](http://blog.gainlo.co/index.php/2017/01/20/arrange-given-numbers-to-form-the-biggest-number-possible/)

@ -1,9 +1,8 @@
Stack
==
# Stack
- Implementation of an interpreter for a small language that does multiplication/addition/etc.
- Design a `MinStack` data structure that supports a `min()` operation that returns the minimum value in the stack in O(1) time.
- Write an algorithm to determine if all of the delimiters in an expression are matched and closed.
- E.g. `{ac[bb]}`, `[dklf(df(kl))d]{}` and `{[[[]]]}` are matched. But `{3234[fd` and `{df][d}` are not.
- [Source](http://blog.gainlo.co/index.php/2016/09/30/uber-interview-question-delimiter-matching/)
- Sort a stack in ascending order using an additional stack.
* Implementation of an interpreter for a small language that does multiplication/addition/etc.
* Design a `MinStack` data structure that supports a `min()` operation that returns the minimum value in the stack in O(1) time.
* Write an algorithm to determine if all of the delimiters in an expression are matched and closed.
* E.g. `{ac[bb]}`, `[dklf(df(kl))d]{}` and `{[[[]]]}` are matched. But `{3234[fd` and `{df][d}` are not.
* [Source](http://blog.gainlo.co/index.php/2016/09/30/uber-interview-question-delimiter-matching/)
* Sort a stack in ascending order using an additional stack.

@ -1,58 +1,57 @@
String
==
# String
- Output list of strings representing a page of hostings given a list of CSV strings.
- Given a list of words, find the word pairs that when concatenated form a palindrome.
- Find the most efficient way to identify what character is out of place in a non-palindrome.
- 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.
- Find all words from a dictionary that are x edit distance away.
- Given a string IP and number n, print all CIDR addresses that cover that range.
- 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`.
- E.g `"(0 | (1 | 0)) & (1 & ((1 | 0) & 0))"`
- 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.
- E.g. `"abba"` and `"redbluebluered"` should return `true`.
- E.g. `"aaaa"` and `"asdasdasdasd"` should return `true`.
- E.g. `"aabb"` and `"xyzabcxzyabc"` should return `false`.
- 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.
- Given a list of names (strings) and the width of a line, design an algorithm to display them using the minimum number of lines.
- Design a spell-checking algorithm.
- Count and say problem.
- Longest substring with `K` unique characters.
- [Source](http://blog.gainlo.co/index.php/2016/04/12/find-the-longest-substring-with-k-unique-characters/)
- Given a set of random strings, write a function that returns a set that groups all the anagrams together.
- [Source](http://blog.gainlo.co/index.php/2016/05/06/group-anagrams/)
- Given a string, find the longest substring without repeating characters. For example, for string `'abccdefgh'`, the longest substring is `'cdefgh'`.
- [Source](http://blog.gainlo.co/index.php/2016/10/07/facebook-interview-longest-substring-without-repeating-characters/)
- Given a string, return the string with duplicate characters removed.
- 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.
- E.g. `'ab*a'`, `'abbbbba'` => `true`.
- E.g. `'ab*b.'`, `'aba'` => `true`.
- E.g. `'abc*'`, `'acccc'` => `false`.
- Given a rectangular grid with letters, search if some word is in the grid.
- Given two strings representing integer numbers (`'123'` , `'30'`) return a string representing the sum of the two numbers: `'153'`.
- 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`.
- Follow up: Assume you don't have the possibility of using `String.contains()` and `String.substring()`. How would you implement this?
- Print all permutations of a given string.
- Parse a string containing numbers and `'+'`, `'-'` and parentheses. Evaluate the expression. `-2+(3-5)` should return `-4`.
- Output a substring with at most `K` unique characters.
- E.g. `'aabc'` and `k` = 2 => `'aab'`.
- Ensure that there are a minimum of `N` dashes between any two of the same characters of a string.
- E.g. `n = 2, string = 'ab-bcdecca'` => `'ab--bcdec--ca'`.
- Find the longest palindrome in a string.
- Give the count and the number following in the series.
- E.g. `1122344`, next: `21221324`, next: `12112211121214`.
- Count and say problem.
- Compress a string by grouping consecutive similar questions together:
- E.g. `'aaabbbcc' => `'a3b3c2'`.
- You have a string consisting of open and closed parentheses, but parentheses may be imbalanced. Make the parentheses balanced and return the new string.
- Given a set of strings, return the smallest subset that contains prefixes for every string.
- E.g. `['foo', 'foog', 'food', 'asdf']` => `['foo', 'asdf']`.
- Write a function that would return all the possible words generated when using a phone (pre-smartphone era) numpad to type.
- Given a dictionary and a word, find the minimum number of deletions needed on the word in order to make it a valid word.
- [Source](http://blog.gainlo.co/index.php/2016/04/29/minimum-number-of-deletions-of-a-string/)
- How to check if a string contains an anagram of another string?
- [Source](http://blog.gainlo.co/index.php/2016/04/08/if-a-string-contains-an-anagram-of-another-string/)
- Find all k-lettered words from a string.
- Given a string of open and close parentheses, find the minimum number of edits needed to balance a string of parentheses.
- Run length encoding - Write a string compress function that returns `'R2G1B1'` given `'RRGB'`.
- Write a function that finds all the different ways you can split up a word into a concatenation of two other words.
* Output list of strings representing a page of hostings given a list of CSV strings.
* Given a list of words, find the word pairs that when concatenated form a palindrome.
* Find the most efficient way to identify what character is out of place in a non-palindrome.
* 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.
* Find all words from a dictionary that are x edit distance away.
* Given a string IP and number n, print all CIDR addresses that cover that range.
* 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`.
* E.g `"(0 | (1 | 0)) & (1 & ((1 | 0) & 0))"`
* 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.
* E.g. `"abba"` and `"redbluebluered"` should return `true`.
* E.g. `"aaaa"` and `"asdasdasdasd"` should return `true`.
* E.g. `"aabb"` and `"xyzabcxzyabc"` should return `false`.
* 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.
* Given a list of names (strings) and the width of a line, design an algorithm to display them using the minimum number of lines.
* Design a spell-checking algorithm.
* Count and say problem.
* Longest substring with `K` unique characters.
* [Source](http://blog.gainlo.co/index.php/2016/04/12/find-the-longest-substring-with-k-unique-characters/)
* Given a set of random strings, write a function that returns a set that groups all the anagrams together.
* [Source](http://blog.gainlo.co/index.php/2016/05/06/group-anagrams/)
* Given a string, find the longest substring without repeating characters. For example, for string `'abccdefgh'`, the longest substring is `'cdefgh'`.
* [Source](http://blog.gainlo.co/index.php/2016/10/07/facebook-interview-longest-substring-without-repeating-characters/)
* Given a string, return the string with duplicate characters removed.
* 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.
* E.g. `'ab*a'`, `'abbbbba'` => `true`.
* E.g. `'ab*b.'`, `'aba'` => `true`.
* E.g. `'abc*'`, `'acccc'` => `false`.
* Given a rectangular grid with letters, search if some word is in the grid.
* Given two strings representing integer numbers (`'123'` , `'30'`) return a string representing the sum of the two numbers: `'153'`.
* 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`.
* Follow up: Assume you don't have the possibility of using `String.contains()` and `String.substring()`. How would you implement this?
* Print all permutations of a given string.
* Parse a string containing numbers and `'+'`, `'-'` and parentheses. Evaluate the expression. `-2+(3-5)` should return `-4`.
* Output a substring with at most `K` unique characters.
* E.g. `'aabc'` and `k` = 2 => `'aab'`.
* Ensure that there are a minimum of `N` dashes between any two of the same characters of a string.
* E.g. `n = 2, string = 'ab-bcdecca'` => `'ab--bcdec--ca'`.
* Find the longest palindrome in a string.
* Give the count and the number following in the series.
* E.g. `1122344`, next: `21221324`, next: `12112211121214`.
* Count and say problem.
* Compress a string by grouping consecutive similar questions together:
* E.g. `'aaabbbcc' =>`'a3b3c2'`.
* You have a string consisting of open and closed parentheses, but parentheses may be imbalanced. Make the parentheses balanced and return the new string.
* Given a set of strings, return the smallest subset that contains prefixes for every string.
* E.g. `['foo', 'foog', 'food', 'asdf']` => `['foo', 'asdf']`.
* Write a function that would return all the possible words generated when using a phone (pre-smartphone era) numpad to type.
* Given a dictionary and a word, find the minimum number of deletions needed on the word in order to make it a valid word.
* [Source](http://blog.gainlo.co/index.php/2016/04/29/minimum-number-of-deletions-of-a-string/)
* How to check if a string contains an anagram of another string?
* [Source](http://blog.gainlo.co/index.php/2016/04/08/if-a-string-contains-an-anagram-of-another-string/)
* Find all k-lettered words from a string.
* Given a string of open and close parentheses, find the minimum number of edits needed to balance a string of parentheses.
* Run length encoding - Write a string compress function that returns `'R2G1B1'` given `'RRGB'`.
* Write a function that finds all the different ways you can split up a word into a concatenation of two other words.

@ -1,27 +1,26 @@
Topics
==
# Topics
## Arrays
## Strings
- Prefix trees (Tries)
- Suffix trees
- Suffix arrays
- KMP
- Rabin-Karp
- Boyer-Moore
* Prefix trees (Tries)
* Suffix trees
* Suffix arrays
* KMP
* Rabin-Karp
* Boyer-Moore
## Sorting
- Bubble sort
- Insertion sort
- Merge sort
- Quick sort
- Selection sort
- Bucket sort
- Radix sort
- Counting sort
* Bubble sort
* Insertion sort
* Merge sort
* Quick sort
* Selection sort
* Bucket sort
* Radix sort
* Counting sort
## Linked Lists
@ -31,59 +30,59 @@ Topics
## Hash tables
- Collision resolution algorithms
* Collision resolution algorithms
## Trees
- BFS
- DFS (inorder, postorder, preorder)
- Height
* BFS
* DFS (inorder, postorder, preorder)
* Height
## Binary Search Trees
- Insert node
- Delete a node
- Find element in BST
- Find min, max element in BST
- Get successor element in tree
- Check if a binary tree is a BST or not
* Insert node
* Delete a node
* Find element in BST
* Find min, max element in BST
* Get successor element in tree
* Check if a binary tree is a BST or not
## Heaps / Priority Queues
- Insert
- Bubble up
- Extract max
- Remove
- Heapify
- Heap sort
* Insert
* Bubble up
* Extract max
* Remove
* Heapify
* Heap sort
## Graphs
- Various implementations
- Adjacency matrix
- Adjacency list
- Adjacency map
- Single-source shortest path
- Dijkstra
- Bellman-Ford
- Topo sort
- MST
- Prim algorithm
- Kruskal's algorithm
- Union Find Data Structure
- Count connected components in a graph
- List strongly connected components in a graph
- Check for bipartite graph
* Various implementations
* Adjacency matrix
* Adjacency list
* Adjacency map
* Single-source shortest path
* Dijkstra
* Bellman-Ford
* Topo sort
* MST
* Prim algorithm
* Kruskal's algorithm
* Union Find Data Structure
* Count connected components in a graph
* List strongly connected components in a graph
* Check for bipartite graph
## Dynamic Programming
- Count Change
- 0-1 Knapsack
* Count Change
* 0-1 Knapsack
## System Design
- http://www.hiredintech.com/system-design/
- https://www.quora.com/How-do-I-prepare-to-answer-design-questions-in-a-technical-interview?redirected_qid=1500023
- http://blog.gainlo.co/index.php/2015/10/22/8-things-you-need-to-know-before-system-design-interviews/
- https://github.com/donnemartin/system-design-primer
- https://github.com/jwasham/coding-interview-university/blob/master/extras/cheat%20sheets/system-design.pdf
* http://www.hiredintech.com/system-design/
* https://www.quora.com/How-do-I-prepare-to-answer-design-questions-in-a-technical-interview?redirected_qid=1500023
* http://blog.gainlo.co/index.php/2015/10/22/8-things-you-need-to-know-before-system-design-interviews/
* https://github.com/donnemartin/system-design-primer
* https://github.com/jwasham/coding-interview-university/blob/master/extras/cheat%20sheets/system-design.pdf

@ -1,36 +1,35 @@
Tree
==
# Tree
- Find the height of a tree.
- Find the longest path from the root to leaf in a tree.
- Find the deepest left leaf of a tree.
- Print all paths of a binary tree.
- [Source](http://blog.gainlo.co/index.php/2016/04/15/print-all-paths-of-a-binary-tree/)
- Second largest element of a BST.
- [Source](http://blog.gainlo.co/index.php/2016/06/03/second-largest-element-of-a-binary-search-tree/)
- Given a binary tree and two nodes, how to find the common ancestor of the two nodes?
- [Source](http://blog.gainlo.co/index.php/2016/07/06/lowest-common-ancestor/)
- Find the lowest common ancestor of two nodes in a binary search tree.
- Print the nodes in an n-ary tree level by level, one printed line per level.
- Given a directory of files and folders (and relevant functions), how would you parse through it to find equivalent files?
- Write a basic file system and implement the commands ls, pwd, mkdir, create, rm, cd, cat, mv.
- Compute the intersection of two binary search trees.
- Given a binary tree, output all the node to leaf paths of it.
- Given a string of characters without spaces, is there a way to break the string into valid words without leftover characters?
- Print a binary tree level by level.
- 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).
- Find the longest path in a binary tree. The path may start and end at any node.
- Determine if a binary tree is a BST.
- Given a binary tree, serialize it into a string. Then deserialize it.
- Print a binary tree by column.
- Given a node, find the next element in a BST.
- Find the shortest subtree that consist of all the deepest nodes. The tree is not binary.
- Print out the sum of each row in a binary tree.
- Pretty print a JSON object.
- Convert a binary tree to a doubly circular linked list.
- Find the second largest number in a binary tree.
- Given a tree, find the longest branch.
- Convert a tree to a linked list.
- Given two trees, write code to find out if tree A is a subtree of tree B.
- Deepest node in a tree.
- [Source](http://blog.gainlo.co/index.php/2016/04/26/deepest-node-in-a-tree/)
* Find the height of a tree.
* Find the longest path from the root to leaf in a tree.
* Find the deepest left leaf of a tree.
* Print all paths of a binary tree.
* [Source](http://blog.gainlo.co/index.php/2016/04/15/print-all-paths-of-a-binary-tree/)
* Second largest element of a BST.
* [Source](http://blog.gainlo.co/index.php/2016/06/03/second-largest-element-of-a-binary-search-tree/)
* Given a binary tree and two nodes, how to find the common ancestor of the two nodes?
* [Source](http://blog.gainlo.co/index.php/2016/07/06/lowest-common-ancestor/)
* Find the lowest common ancestor of two nodes in a binary search tree.
* Print the nodes in an n-ary tree level by level, one printed line per level.
* Given a directory of files and folders (and relevant functions), how would you parse through it to find equivalent files?
* Write a basic file system and implement the commands ls, pwd, mkdir, create, rm, cd, cat, mv.
* Compute the intersection of two binary search trees.
* Given a binary tree, output all the node to leaf paths of it.
* Given a string of characters without spaces, is there a way to break the string into valid words without leftover characters?
* Print a binary tree level by level.
* 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).
* Find the longest path in a binary tree. The path may start and end at any node.
* Determine if a binary tree is a BST.
* Given a binary tree, serialize it into a string. Then deserialize it.
* Print a binary tree by column.
* Given a node, find the next element in a BST.
* Find the shortest subtree that consist of all the deepest nodes. The tree is not binary.
* Print out the sum of each row in a binary tree.
* Pretty print a JSON object.
* Convert a binary tree to a doubly circular linked list.
* Find the second largest number in a binary tree.
* Given a tree, find the longest branch.
* Convert a tree to a linked list.
* Given two trees, write code to find out if tree A is a subtree of tree B.
* Deepest node in a tree.
* [Source](http://blog.gainlo.co/index.php/2016/04/26/deepest-node-in-a-tree/)

@ -1,94 +1,93 @@
Design Questions
==
# Design Questions
## Guides
- https://github.com/donnemartin/system-design-primer
- https://github.com/checkcheckzz/system-design-interview
- https://github.com/shashank88/system_design
- https://gist.github.com/vasanthk/485d1c25737e8e72759f
- http://www.puncsky.com/blog/2016/02/14/crack-the-system-design-interview/
- https://www.palantir.com/2011/10/how-to-rock-a-systems-design-interview/
- http://blog.gainlo.co/index.php/2017/04/13/system-design-interviews-part-ii-complete-guide-google-interview-preparation/
* https://github.com/donnemartin/system-design-primer
* https://github.com/checkcheckzz/system-design-interview
* https://github.com/shashank88/system_design
* https://gist.github.com/vasanthk/485d1c25737e8e72759f
* http://www.puncsky.com/blog/2016/02/14/crack-the-system-design-interview/
* https://www.palantir.com/2011/10/how-to-rock-a-systems-design-interview/
* http://blog.gainlo.co/index.php/2017/04/13/system-design-interviews-part-ii-complete-guide-google-interview-preparation/
## Flow
#### A. Understand the problem and scope
- Define the use cases, with interviewer's help.
- Suggest additional features.
- Remove items that interviewer deems out of scope.
- Assume high availability is required, add as a use case.
* Define the use cases, with interviewer's help.
* Suggest additional features.
* Remove items that interviewer deems out of scope.
* Assume high availability is required, add as a use case.
#### B. Think about constraints
- Ask how many requests per month.
- Ask how many requests per second (they may volunteer it or make you do the math).
- Estimate reads vs. writes percentage.
- Keep 80/20 rule in mind when estimating.
- How much data written per second.
- Total storage required over 5 years.
- How much data reads per second.
* Ask how many requests per month.
* Ask how many requests per second (they may volunteer it or make you do the math).
* Estimate reads vs. writes percentage.
* Keep 80/20 rule in mind when estimating.
* How much data written per second.
* Total storage required over 5 years.
* How much data reads per second.
#### C. Abstract design
- Layers (service, data, caching).
- Infrastructure: load balancing, messaging.
- Rough overview of any key algorithm that drives the service.
- Consider bottlenecks and determine solutions.
* Layers (service, data, caching).
* Infrastructure: load balancing, messaging.
* Rough overview of any key algorithm that drives the service.
* Consider bottlenecks and determine solutions.
Source: https://github.com/jwasham/coding-interview-university#system-design-scalability-data-handling
## Grading Rubrics
- Problem Solving - How systematic is your approach to solving the problem step-by-step? Break down a problem into its core components.
- Communication - How well do you explain your idea and communicate it with others?
- Evaluation - How do you evaluate your system? Are you aware of the trade-offs made? How can you optimize it?
- Estimation - How fast does your system need to be? How much space does it need? How much load will it experience?
* Problem Solving - How systematic is your approach to solving the problem step-by-step? Break down a problem into its core components.
* Communication - How well do you explain your idea and communicate it with others?
* Evaluation - How do you evaluate your system? Are you aware of the trade-offs made? How can you optimize it?
* Estimation - How fast does your system need to be? How much space does it need? How much load will it experience?
## Specific Topics
- URL Shortener
- http://stackoverflow.com/questions/742013/how-to-code-a-url-shortener
- http://blog.gainlo.co/index.php/2016/03/08/system-design-interview-question-create-tinyurl-system/
- https://www.interviewcake.com/question/python/url-shortener
- Collaborative Editor
- http://blog.gainlo.co/index.php/2016/03/22/system-design-interview-question-how-to-design-google-docs/
- Photo Sharing App
- http://blog.gainlo.co/index.php/2016/03/01/system-design-interview-question-create-a-photo-sharing-app/
- Social Network Feed
- http://blog.gainlo.co/index.php/2016/02/17/system-design-interview-question-how-to-design-twitter-part-1/
- http://blog.gainlo.co/index.php/2016/02/24/system-design-interview-question-how-to-design-twitter-part-2/
- http://blog.gainlo.co/index.php/2016/03/29/design-news-feed-system-part-1-system-design-interview-questions/
- Trending Algorithm
- http://blog.gainlo.co/index.php/2016/05/03/how-to-design-a-trending-algorithm-for-twitter/
- Facebook Chat
- http://blog.gainlo.co/index.php/2016/04/19/design-facebook-chat-function/
- Key Value Store
- http://blog.gainlo.co/index.php/2016/06/14/design-a-key-value-store-part-i/
- http://blog.gainlo.co/index.php/2016/06/21/design-key-value-store-part-ii/
- Recommendation System
- http://blog.gainlo.co/index.php/2016/05/24/design-a-recommendation-system/
- Cache System
- http://blog.gainlo.co/index.php/2016/05/17/design-a-cache-system/
- E-commerce Website
- http://blog.gainlo.co/index.php/2016/08/22/design-ecommerce-website-part/
- http://blog.gainlo.co/index.php/2016/08/28/design-ecommerce-website-part-ii/
- Web Crawler
- http://blog.gainlo.co/index.php/2016/06/29/build-web-crawler/
- http://www.makeuseof.com/tag/how-do-search-engines-work-makeuseof-explains/
- https://www.quora.com/How-can-I-build-a-web-crawler-from-scratch/answer/Chris-Heller
- YouTube
- http://blog.gainlo.co/index.php/2016/10/22/design-youtube-part/
- http://blog.gainlo.co/index.php/2016/11/04/design-youtube-part-ii/
- Hit Counter
- http://blog.gainlo.co/index.php/2016/09/12/dropbox-interview-design-hit-counter/
- Facebook Graph Search
- Design [Lyft Line](https://www.lyft.com/line).
- Design a promo code system (with same promo code, randomly generated promo code, and promo code with conditions).
- Model a university.
- How would you implement Pacman?
- Sketch out an implementation of Asteroids.
- Implement a spell checker.
- Design the rubik cube.
- Design a high-level interface to be used for card games (e.g. poker, blackjack etc).
* URL Shortener
* http://stackoverflow.com/questions/742013/how-to-code-a-url-shortener
* http://blog.gainlo.co/index.php/2016/03/08/system-design-interview-question-create-tinyurl-system/
* https://www.interviewcake.com/question/python/url-shortener
* Collaborative Editor
* http://blog.gainlo.co/index.php/2016/03/22/system-design-interview-question-how-to-design-google-docs/
* Photo Sharing App
* http://blog.gainlo.co/index.php/2016/03/01/system-design-interview-question-create-a-photo-sharing-app/
* Social Network Feed
* http://blog.gainlo.co/index.php/2016/02/17/system-design-interview-question-how-to-design-twitter-part-1/
* http://blog.gainlo.co/index.php/2016/02/24/system-design-interview-question-how-to-design-twitter-part-2/
* http://blog.gainlo.co/index.php/2016/03/29/design-news-feed-system-part-1-system-design-interview-questions/
* Trending Algorithm
* http://blog.gainlo.co/index.php/2016/05/03/how-to-design-a-trending-algorithm-for-twitter/
* Facebook Chat
* http://blog.gainlo.co/index.php/2016/04/19/design-facebook-chat-function/
* Key Value Store
* http://blog.gainlo.co/index.php/2016/06/14/design-a-key-value-store-part-i/
* http://blog.gainlo.co/index.php/2016/06/21/design-key-value-store-part-ii/
* Recommendation System
* http://blog.gainlo.co/index.php/2016/05/24/design-a-recommendation-system/
* Cache System
* http://blog.gainlo.co/index.php/2016/05/17/design-a-cache-system/
* E-commerce Website
* http://blog.gainlo.co/index.php/2016/08/22/design-ecommerce-website-part/
* http://blog.gainlo.co/index.php/2016/08/28/design-ecommerce-website-part-ii/
* Web Crawler
* http://blog.gainlo.co/index.php/2016/06/29/build-web-crawler/
* http://www.makeuseof.com/tag/how-do-search-engines-work-makeuseof-explains/
* https://www.quora.com/How-can-I-build-a-web-crawler-from-scratch/answer/Chris-Heller
* YouTube
* http://blog.gainlo.co/index.php/2016/10/22/design-youtube-part/
* http://blog.gainlo.co/index.php/2016/11/04/design-youtube-part-ii/
* Hit Counter
* http://blog.gainlo.co/index.php/2016/09/12/dropbox-interview-design-hit-counter/
* Facebook Graph Search
* Design [Lyft Line](https://www.lyft.com/line).
* Design a promo code system (with same promo code, randomly generated promo code, and promo code with conditions).
* Model a university.
* How would you implement Pacman?
* Sketch out an implementation of Asteroids.
* Implement a spell checker.
* Design the rubik cube.
* Design a high-level interface to be used for card games (e.g. poker, blackjack etc).

@ -1,81 +1,80 @@
Collaborative Document Editor
==
# Collaborative Document Editor
## Variants
- Design Google docs.
- Design a collaborative code editor like Coderpad/Codepile.
- Design a collaborative markdown editor.
* Design Google docs.
* Design a collaborative code editor like Coderpad/Codepile.
* Design a collaborative markdown editor.
## Requirements Gathering
- What is the intended platform?
- Web
- What features are required?
- Creating a document
- Editing a document
- Sharing a document
- Bonus features
- Document revisions and reverting
- Searching
- Commenting
- Chatting
- Executing code (in the case of code editor)
- What is in a document?
- Text
- Images
- Which metrics should we optimize for?
- Loading time
- Synchronization
- Throughput
* What is the intended platform?
* Web
* What features are required?
* Creating a document
* Editing a document
* Sharing a document
* Bonus features
* Document revisions and reverting
* Searching
* Commenting
* Chatting
* Executing code (in the case of code editor)
* What is in a document?
* Text
* Images
* Which metrics should we optimize for?
* Loading time
* Synchronization
* Throughput
## Core Components
- Front end
- WebSockets/long polling for real-time communication between front end and back end.
- Back end services behind a reverse proxy.
- Reverse proxy will proxy the requests to the right server.
- Split into a few services for different purposes.
- The benefit of this is that each service can use different languages that best suits its purpose.
- API servers for non-collaborative features and endpoints.
- Ruby/Rails/Django for the server that deals with CRUD operations on data models where performance is not that crucial.
- WebSocket servers for handling document edits and publishing updates to listeners.
- Possibly Node/Golang for WebSocket server which will need high performance as updates are frequent.
- Task queue to persist document updates to the database.
- ELB in front of back end servers.
- MySQL database.
- S3 and CDN for images.
* Front end
* WebSockets/long polling for real-time communication between front end and back end.
* Back end services behind a reverse proxy.
* Reverse proxy will proxy the requests to the right server.
* Split into a few services for different purposes.
* The benefit of this is that each service can use different languages that best suits its purpose.
* API servers for non-collaborative features and endpoints.
* Ruby/Rails/Django for the server that deals with CRUD operations on data models where performance is not that crucial.
* WebSocket servers for handling document edits and publishing updates to listeners.
* Possibly Node/Golang for WebSocket server which will need high performance as updates are frequent.
* Task queue to persist document updates to the database.
* ELB in front of back end servers.
* MySQL database.
* S3 and CDN for images.
## Data Modeling
- What kind of database to use?
- Data is quite structured. Would go with SQL.
- Design the necessary tables, its columns and its relations.
- `users`
- `id`
- `name`
- `document`
- `id`
- `owner_id`
- `permissions`
- `id`
- `name`
- `document_permissions`
- `id`
- `document_id`
- `user_id`
* What kind of database to use?
* Data is quite structured. Would go with SQL.
* Design the necessary tables, its columns and its relations.
* `users`
* `id`
* `name`
* `document`
* `id`
* `owner_id`
* `permissions`
* `id`
* `name`
* `document_permissions`
* `id`
* `document_id`
* `user_id`
## Collaborative Editing - Client
- Upon loading of the page and document, the client should connect to the WebSocket server over the WebSocket protocol `ws://`.
- Upon connection, perform a time sync with the server, possibly via Network Time Protocol (NTP).
- 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:
- 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.
- 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.
- 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?
- (a) Changing a character/word, (b) inserting a character/word/image, (c) deleting a character/word.
- 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.
- Updates can also be throttled and batched, to avoid flooding the web server with requests. For example, if a user inserts a
* Upon loading of the page and document, the client should connect to the WebSocket server over the WebSocket protocol `ws://`.
* Upon connection, perform a time sync with the server, possibly via Network Time Protocol (NTP).
* 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:
* 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.
* 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.
* 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?
* (a) Changing a character/word, (b) inserting a character/word/image, (c) deleting a character/word.
* 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.
* Updates can also be throttled and batched, to avoid flooding the web server with requests. For example, if a user inserts a
## Back End
@ -83,21 +82,21 @@ The back end is split into a few portions: WebSocket server for receiving and br
## WebSocket Server
- 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.
- 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.
- Each document corresponds to a room (more of namespace). Users can subscribe to the events happening within a room.
- When a action delta is being received, blast it out to the listeners within the room and add it to the task queue.
* 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.
* 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.
* Each document corresponds to a room (more of namespace). Users can subscribe to the events happening within a room.
* When a action delta is being received, blast it out to the listeners within the room and add it to the task queue.
## CRUD Server
- Provides APIs for reading and writing non-document-related data, such as users, permissions.
* Provides APIs for reading and writing non-document-related data, such as users, permissions.
## Task Queue + Worker Service
- Worker service retrieves messages from the task queue and writes the updated documents to the database in an async fashion.
- 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.
- 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.
- 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.
* Worker service retrieves messages from the task queue and writes the updated documents to the database in an async fashion.
* 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.
* 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.
* 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.
## Document Persistence
@ -105,4 +104,4 @@ TODO
###### References
- http://blog.gainlo.co/index.php/2016/03/22/system-design-interview-question-how-to-design-google-docs/
* http://blog.gainlo.co/index.php/2016/03/22/system-design-interview-question-how-to-design-google-docs/

@ -1,46 +1,45 @@
News Feed
==
# News Feed
## Variants
- Design Facebook news feed.
- Design Twitter news feed.
- Design Quora feed.
- Design Instagram feed.
* Design Facebook news feed.
* Design Twitter news feed.
* Design Quora feed.
* Design Instagram feed.
## Requirements Gathering
- What is the intended platform?
- Mobile (mobile web or native)? Web? Desktop?
- What features are required?
- CRUD posts.
- Commenting on posts.
- Sharing posts.
- Trending posts?
- Tag people?
- Hashtags?
- What is in a news feed post?
- Author.
- Content.
- Media.
- Tags?
- Hashtags?
- Comments/Replies.
- Operations:
- CRUD
- Commenting/replying to a post.
- What is in a news feed?
- Sequence of posts.
- Query pattern: query for a user's ranked news feed.
- Operations:
- Append - Fetch more posts.
- Delete - I don't want to see this.
- Which metrics should we optimize for?
- User retention.
- Ads revenue.
- Fast loading time.
- Bandwidth.
- Server costs.
* What is the intended platform?
* Mobile (mobile web or native)? Web? Desktop?
* What features are required?
* CRUD posts.
* Commenting on posts.
* Sharing posts.
* Trending posts?
* Tag people?
* Hashtags?
* What is in a news feed post?
* Author.
* Content.
* Media.
* Tags?
* Hashtags?
* Comments/Replies.
* Operations:
* CRUD
* Commenting/replying to a post.
* What is in a news feed?
* Sequence of posts.
* Query pattern: query for a user's ranked news feed.
* Operations:
* Append - Fetch more posts.
* Delete - I don't want to see this.
* Which metrics should we optimize for?
* User retention.
* Ads revenue.
* Fast loading time.
* Bandwidth.
* Server costs.
## Core Components
@ -48,14 +47,14 @@ TODO
## Data modeling
- What kind of database to use?
- Data is quite structured. Would go with SQL.
- Design the necessary tables, its columns and its relations.
- `users`
- `posts`
- `likes`
- `follows`
- `comments`
* What kind of database to use?
* Data is quite structured. Would go with SQL.
* Design the necessary tables, its columns and its relations.
* `users`
* `posts`
* `likes`
* `follows`
* `comments`
> 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.
>
@ -68,48 +67,49 @@ TODO
> 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).
>
> The disadvantages are obvious:
> - Data redundancy. We are storing redundant data, which occupies storage space (classic time-space trade-off).
> - 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.
> - 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.
>
> * Data redundancy. We are storing redundant data, which occupies storage space (classic time-space trade-off).
> * 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.
> * 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.
## Feed Display
- The most straightforward way is to fetch posts from all the people you follow and render them sorted by time.
- There can be many posts to fetch. How many posts should you fetch?
- What are the pagination approaches and the pros and cons of each approach?
- Offset by page size
- Offset by time
- What data should the post contain when you initially fetch them?
- Lazy loading approach for loading associated data: media, comments, people who liked the post.
- Media
- If the post contains media such as images and videos, how should they be handled? Should they be loaded on the spot?
- A better way would be to fetch images only when they are about to enter the viewport.
- Videos should not autoplay. Only fetch the thumbnail for the video, and only play the video when user clicks play.
- 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.
- Comments
- Should you fetch all the comments for a post? For posts by celebrities, they can contain a few hundred or thousand comments.
- Maybe fetch the top few comments and display them under the post, and the user is given the choice to "show all comments".
- How does the user request for new content?
- Infinite scrolling.
- User has to tap next page.
* The most straightforward way is to fetch posts from all the people you follow and render them sorted by time.
* There can be many posts to fetch. How many posts should you fetch?
* What are the pagination approaches and the pros and cons of each approach?
* Offset by page size
* Offset by time
* What data should the post contain when you initially fetch them?
* Lazy loading approach for loading associated data: media, comments, people who liked the post.
* Media
* If the post contains media such as images and videos, how should they be handled? Should they be loaded on the spot?
* A better way would be to fetch images only when they are about to enter the viewport.
* Videos should not autoplay. Only fetch the thumbnail for the video, and only play the video when user clicks play.
* 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.
* Comments
* Should you fetch all the comments for a post? For posts by celebrities, they can contain a few hundred or thousand comments.
* Maybe fetch the top few comments and display them under the post, and the user is given the choice to "show all comments".
* How does the user request for new content?
* Infinite scrolling.
* User has to tap next page.
## Feed Ranking
- First select features/signals that are relevant and then figure out how to combine them to calculate a final score.
- How do you show the relevant posts that the user is interested in?
- 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.
- Popularity - How many likes and comments does the post have? Does the user usually like posts by that person?
- 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.
- A common strategy is to calculate a post score based on various features and rank posts by its score.
- 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.
- Edge Rank basically is using three signals: affinity score, edge weight and time decay.
- 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.
- Edge weight (e) - Edge weight basically reflects importance of each edge. For instance, comments are worth more than likes.
- Time decay (d) - The older the story, the less likely users find it interesting.
- Affinity score
- 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.
- 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.
- A good ranking system can improve some core metrics - user retention, ads revenue, etc.
* First select features/signals that are relevant and then figure out how to combine them to calculate a final score.
* How do you show the relevant posts that the user is interested in?
* 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.
* Popularity - How many likes and comments does the post have? Does the user usually like posts by that person?
* 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.
* A common strategy is to calculate a post score based on various features and rank posts by its score.
* 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.
* Edge Rank basically is using three signals: affinity score, edge weight and time decay.
* 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.
* Edge weight (e) - Edge weight basically reflects importance of each edge. For instance, comments are worth more than likes.
* Time decay (d) - The older the story, the less likely users find it interesting.
* Affinity score
* 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.
* 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.
* A good ranking system can improve some core metrics - user retention, ads revenue, etc.
## Feed Publishing
@ -119,46 +119,46 @@ TODO. Refer to http://blog.gainlo.co/index.php/2016/04/05/design-news-feed-syste
#### Tagging feature
- Have a `tags` table that stores the relation between a post and the people tagged in it.
* Have a `tags` table that stores the relation between a post and the people tagged in it.
#### Sharing feature
- Add a column to `posts` table called `original_post_id`.
- What should happen when the original post is deleted?
- The shared `posts` have to be deleted too.
* Add a column to `posts` table called `original_post_id`.
* What should happen when the original post is deleted?
* The shared `posts` have to be deleted too.
#### Notifications feature
- When should notifications happen?
- Can the user subscribe to only certain types of notifications?
* When should notifications happen?
* Can the user subscribe to only certain types of notifications?
#### Trending feature
- What constitutes trending? What signals would you look at? What weight would you give to each signal?
- Most frequent hashtags over the last N hours.
- Hottest search queries.
- Fetch the recent most popular feeds and extract some common words or phrases.
* What constitutes trending? What signals would you look at? What weight would you give to each signal?
* Most frequent hashtags over the last N hours.
* Hottest search queries.
* Fetch the recent most popular feeds and extract some common words or phrases.
#### Search feature
- How would you index the data?
* How would you index the data?
## Scalability
- Master-slave replication.
- Write to master database and read from replica databases/in-memory data store.
- 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.
- Data for real-time queries should be in memory, disk is for writes only.
- Pre-computation offline.
- Tracking number of likes and comments.
- Expensive to do a `COUNT` on the `likes` and `comments` for a post.
- 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.
- Load balancer in front of your API servers.
- Partitioning the data.
* Master-slave replication.
* Write to master database and read from replica databases/in-memory data store.
* 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.
* Data for real-time queries should be in memory, disk is for writes only.
* Pre-computation offline.
* Tracking number of likes and comments.
* Expensive to do a `COUNT` on the `likes` and `comments` for a post.
* 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.
* Load balancer in front of your API servers.
* Partitioning the data.
###### References
- [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/)
- [Design News Feed System (Part 1)](http://blog.gainlo.co/index.php/2016/04/05/design-news-feed-system-part-2/)
- [Etsy Activity Feeds Architecture](https://www.slideshare.net/danmckinley/etsy-activity-feeds-architecture)
- [Big Data in Real-Time at Twitter](https://www.slideshare.net/nkallen/q-con-3770885)
* [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/)
* [Design News Feed System (Part 1)](http://blog.gainlo.co/index.php/2016/04/05/design-news-feed-system-part-2/)
* [Etsy Activity Feeds Architecture](https://www.slideshare.net/danmckinley/etsy-activity-feeds-architecture)
* [Big Data in Real-Time at Twitter](https://www.slideshare.net/nkallen/q-con-3770885)

@ -1,6 +1,5 @@
Search Engine
==
# Search Engine
###### References
- [How Do Search Engines Work?](http://www.makeuseof.com/tag/how-do-search-engines-work-makeuseof-explains/)
* [How Do Search Engines Work?](http://www.makeuseof.com/tag/how-do-search-engines-work-makeuseof-explains/)

@ -1,8 +1,7 @@
Databases
==
# Databases
## General
- How should you store passwords in a database?
- http://www.geeksforgeeks.org/store-password-database/
- https://nakedsecurity.sophos.com/2013/11/20/serious-security-how-to-store-your-users-passwords-safely/
* How should you store passwords in a database?
* http://www.geeksforgeeks.org/store-password-database/
* https://nakedsecurity.sophos.com/2013/11/20/serious-security-how-to-store-your-users-passwords-safely/

@ -1,6 +1,5 @@
Networking
==
# Networking
- 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).
- Describe what happens when you enter a url in the web browser.
- Define UDP/TCP and give an example of both.
* 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).
* Describe what happens when you enter a url in the web browser.
* Define UDP/TCP and give an example of both.

File diff suppressed because it is too large Load Diff

@ -1,20 +1,19 @@
Security
==
# Security
## Encryption
#### Symmetrical Encryption
- Symmetrical encryption is a type of encryption where one key can be used to encrypt messages and also decrypt the same message.
- Symmetrical encryption is usually much less computationally expensive as compared to asymmetric encryption.
- Often called "shared secret" encryption, or "secret key" encryption.
- To use a symmetric encryption scheme, the sender and receiver must securely share a key in advance. This sharing can be done via asymmetric encryption.
* Symmetrical encryption is a type of encryption where one key can be used to encrypt messages and also decrypt the same message.
* Symmetrical encryption is usually much less computationally expensive as compared to asymmetric encryption.
* Often called "shared secret" encryption, or "secret key" encryption.
* To use a symmetric encryption scheme, the sender and receiver must securely share a key in advance. This sharing can be done via asymmetric encryption.
#### Asymmetric Encryption
- A pair of keys are required: a **private key** and a **public key**. Public keys can be shared with anyone while private keys should be kept secret and known only to the owner.
- A private key can be used to decrypt a message encrypted by a public key. A successful decryption verifies that the holder possesses the private key.
- Also known as public key cryptography.
* A pair of keys are required: a **private key** and a **public key**. Public keys can be shared with anyone while private keys should be kept secret and known only to the owner.
* A private key can be used to decrypt a message encrypted by a public key. A successful decryption verifies that the holder possesses the private key.
* Also known as public key cryptography.
## Public Key Infrastructure
@ -22,7 +21,7 @@ A public key infrastructure (PKI) is a system for the creation, storage, and dis
###### References
- https://www.wikiwand.com/en/Public_key_infrastructure
* https://www.wikiwand.com/en/Public_key_infrastructure
## SSH
@ -64,4 +63,4 @@ Authentication using SSH key pairs begins after the symmetric encryption has bee
###### References
- https://www.digitalocean.com/community/tutorials/understanding-the-ssh-encryption-and-connection-process
* https://www.digitalocean.com/community/tutorials/understanding-the-ssh-encryption-and-connection-process

@ -1,77 +1,25 @@
Snake Game
==
# Snake Game
Design a snake game that is to be played in web browser.
Client: React + Redux
Rendering:
Pixel-based graphics. Depending on the intended resolution, can divide the screen into N * M pixels. Can dynamically calculate the size of each pixel.
Rendering: Pixel-based graphics. Depending on the intended resolution, can divide the screen into N \* M pixels. Can dynamically calculate the size of each pixel.
Fruit: One pixel.
Snake body: One pixel width made up of connected pixels.
Fruit: One pixel. Snake body: One pixel width made up of connected pixels.
Model:
{
fruit: {
x, y
},
snake: {
points: [(x, y), ...] # head is at index 0
direction: north/south/east/west
}
speed: 500,
points: 0
}
Model: { fruit: { x, y }, snake: { points: [(x, y), ...] # head is at index 0 direction: north/south/east/west } speed: 500, points: 0 }
function update() {
next_loc = points[0] + (x, y) # Depends on the direction
if (snake.points.find(next_loc) > 0) {
// die
}
let pts = snake.points;
if (!isEqual(next_loc, fruit)) {
pts = points.removeLast();
} else {
generate_fruit();
points++;
}
snake.points = [next_loc, ...pts];
function update() { next_loc = points[0] + (x, y) # Depends on the direction if (snake.points.find(next_loc) > 0) { // die } let pts = snake.points; if (!isEqual(next_loc, fruit)) { pts = points.removeLast(); } else { generate_fruit(); points++; } snake.points = [next_loc, ...pts];
// Boundary checking -> die
}
// Boundary checking -> die }
function generate_fruit() {
// Cannot generate on my own body.
function generate_fruit() { // Cannot generate on my own body.
// First approach: while on body, generate
let next_fruit_location = random_location();
while (snake.points.find(next_fruit_location) > 0) {
next_fruit_location = random_location();
}
fruit = next_fruit_location
// First approach: while on body, generate let next_fruit_location = random_location(); while (snake.points.find(next_fruit_location) > 0) { next_fruit_location = random_location(); } fruit = next_fruit_location
// Second approach: brute force
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
let point = { x: i, y: j }
if (snake.points.find(next_fruit_location) === -1) {
fruit = point
}
}
}
// Second approach: brute force for (let i = 0; i < rows; i++) { for (let j = 0; j < cols; j++) { let point = { x: i, y: j } if (snake.points.find(next_fruit_location) === -1) { fruit = point } } }
// Third approach: brute force with random
const available_points = []
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
let point = { x: i, y: j }
if (snake.points.find(next_fruit_location) === -1) {
available_points.push(point);
}
}
}
fruit = _.sample(available_points);
}
// Third approach: brute force with random const available*points = [] for (let i = 0; i < rows; i++) { for (let j = 0; j < cols; j++) { let point = { x: i, y: j } if (snake.points.find(next_fruit_location) === -1) { available_points.push(point); } } } fruit = *.sample(available_points); }
setInterval(update, speed);

@ -1,22 +1,21 @@
Software Engineering
==
# Software Engineering
## What is the difference between an interface and abstract class?
**Abstract Class**
- For an abstract class, a method must be declared as abstract. An abstract method doesn't have an implementation.
- The Abstract methods can be declared with Access modifiers like public, internal, protected, etc. When implementing these methods in a subclass, you must define them with the same (or a less restricted) visibility.
- Abstract classes can contain variables and concrete methods.
- A class can Inherit only one Abstract class. Hence multiple inheritance is not possible for an Abstract class.
- Abstract is object-oriented. It offers the basic data an 'object' should have and/or functions it should be able to do. It is concerned with the object's basic characteristics: what it has and what it can do. Hence objects which inherit from the same abstract class share the basic characteristics (generalization).
- Abstract class establishes "is a" relation with concrete classes.
* For an abstract class, a method must be declared as abstract. An abstract method doesn't have an implementation.
* The Abstract methods can be declared with Access modifiers like public, internal, protected, etc. When implementing these methods in a subclass, you must define them with the same (or a less restricted) visibility.
* Abstract classes can contain variables and concrete methods.
* A class can Inherit only one Abstract class. Hence multiple inheritance is not possible for an Abstract class.
* Abstract is object-oriented. It offers the basic data an 'object' should have and/or functions it should be able to do. It is concerned with the object's basic characteristics: what it has and what it can do. Hence objects which inherit from the same abstract class share the basic characteristics (generalization).
* Abstract class establishes "is a" relation with concrete classes.
**Interface**
- For an interface, all the methods are abstract by default. So one cannot declare variables or concrete methods in interfaces.
- All methods declared in an interface must be public.
- Interfaces cannot contain variables and concrete methods except constants.
- A class can implement many interfaces. Hence multiple interface inheritance is possible.
- Interface is functionality-oriented. It defines functionalities an object should have. Regardless what object it is, as long as it can do these functionalities, which are defined in the interface, it's fine. It ignores everything else. An object/class can contain several (groups of) functionalities; hence it is possible for a class to implement multiple interfaces.
- Interface provides "has a" capability for classes.
* For an interface, all the methods are abstract by default. So one cannot declare variables or concrete methods in interfaces.
* All methods declared in an interface must be public.
* Interfaces cannot contain variables and concrete methods except constants.
* A class can implement many interfaces. Hence multiple interface inheritance is possible.
* Interface is functionality-oriented. It defines functionalities an object should have. Regardless what object it is, as long as it can do these functionalities, which are defined in the interface, it's fine. It ignores everything else. An object/class can contain several (groups of) functionalities; hence it is possible for a class to implement multiple interfaces.
* Interface provides "has a" capability for classes.

@ -1,10 +1,9 @@
Accessibility
==
# Accessibility
## Glossary
- **Accessibility** -
- **WAI-ARIA** - Web Accessibility Initiative - Accessible Rich Internet Applications. Commonly shortened to ARIA.
* **Accessibility** -
* **WAI-ARIA** - Web Accessibility Initiative - Accessible Rich Internet Applications. Commonly shortened to ARIA.
## What is Accessibility?
@ -14,71 +13,73 @@ Making sure that the content and the websites we create are usable to people wit
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).
- **Perceivable** - Web content is made available to the senses - sight, hearing, and/or touch.
- Text Alternatives: Provide text alternatives for any non-text content.
- Time-based Media: Provide alternatives for time-based media.
- Adaptable: Create content that can be presented in different ways (for example simpler layout) without losing information or structure.
- Distinguishable: Make it easier for users to see and hear content including separating foreground from background.
- **Operable** - Interface forms, controls, and navigation are operable.
- Keyboard Accessible: Make all functionality available from a keyboard.
- Enough Time: Provide users enough time to read and use content.
- Seizures: Do not design content in a way that is known to cause seizures.
- Navigable: Provide ways to help users navigate, find content, and determine where they are.
- **Understandable** - Content and interface are understandable.
- Readable: Make text content readable and understandable.
- Predictable: Make Web pages appear and operate in predictable ways.
- Input Assistance: Help users avoid and correct mistakes.
- **Robust** - Content can be used reliably by a wide variety of user agents, including assistive technologies.
- Compatible: Maximize compatibility with current and future user agents, including assistive technologies.
* **Perceivable** - Web content is made available to the senses - sight, hearing, and/or touch.
* Text Alternatives: Provide text alternatives for any non-text content.
* Time-based Media: Provide alternatives for time-based media.
* Adaptable: Create content that can be presented in different ways (for example simpler layout) without losing information or structure.
* Distinguishable: Make it easier for users to see and hear content including separating foreground from background.
* **Operable** - Interface forms, controls, and navigation are operable.
* Keyboard Accessible: Make all functionality available from a keyboard.
* Enough Time: Provide users enough time to read and use content.
* Seizures: Do not design content in a way that is known to cause seizures.
* Navigable: Provide ways to help users navigate, find content, and determine where they are.
* **Understandable** - Content and interface are understandable.
* Readable: Make text content readable and understandable.
* Predictable: Make Web pages appear and operate in predictable ways.
* Input Assistance: Help users avoid and correct mistakes.
* **Robust** - Content can be used reliably by a wide variety of user agents, including assistive technologies.
* Compatible: Maximize compatibility with current and future user agents, including assistive technologies.
**Source:** http://webaim.org/standards/wcag/checklist
## Focus
- Making sure your application has a sensible tab order is important.
- HTML forms and inputs are focusable and handle keyboard events by default.
- Focus tab order relies on the DOM order in the HTML.
- Be careful when using CSS when changing the order of elements on the screen, it can cause the order to be unintuitive and messy.
- `tabindex` attribute:
- `-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.
- `0`: In the natural tab order and can be programatically focused.
- `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.
- Add focus behavior to interactive controls, like buttons, tabs, dropdowns, stuff that users will interactive with.
- Use skip links to allow users to skip directly to the main content without having to tab through all the navigation.
- `document.activeElement` is useful in tracking the current element that has focus on.
* Making sure your application has a sensible tab order is important.
* HTML forms and inputs are focusable and handle keyboard events by default.
* Focus tab order relies on the DOM order in the HTML.
* Be careful when using CSS when changing the order of elements on the screen, it can cause the order to be unintuitive and messy.
* `tabindex` attribute:
* `-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.
* `0`: In the natural tab order and can be programatically focused.
* `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.
* Add focus behavior to interactive controls, like buttons, tabs, dropdowns, stuff that users will interactive with.
* Use skip links to allow users to skip directly to the main content without having to tab through all the navigation.
* `document.activeElement` is useful in tracking the current element that has focus on.
## Semantics
- Using proper labeling not only helps accessibility but it makes the element easier to target for all users!
- Use `<label>` with `for` attributes for form elements.
- Use `alt` attribute for `<img>` elements. Alt text must describe the image.
- TODO
* Using proper labeling not only helps accessibility but it makes the element easier to target for all users!
* Use `<label>` with `for` attributes for form elements.
* Use `alt` attribute for `<img>` elements. Alt text must describe the image.
* TODO
## Navigating Content
- MacOS comes built-in with VoiceOver. Press <kbd>CMD</kbd> + <kbd>F5</kbd> to activate.
- Activate Web Rotor with <kbd>Ctrl</kbd> + <kbd>Option</kbd> + <kbd>U</kbd>. Web Rotor displays landmarks, headings, links and more on the page and allows you to jump to them directly.
- Heading weight should be decided by its importance on the page and not how big it should look, as the heading tag chosen affects the order the headings are listed on screen readers.
- Use HTML5 semantic tags like `<main>`, `<nav>`, `<header>`, `<aside>`, `<article>`, `<section>`, `<footer>` to indicate landmarks on the page.
* MacOS comes built-in with VoiceOver. Press <kbd>CMD</kbd> + <kbd>F5</kbd> to activate.
* Activate Web Rotor with <kbd>Ctrl</kbd> + <kbd>Option</kbd> + <kbd>U</kbd>. Web Rotor displays landmarks, headings, links and more on the page and allows you to jump to them directly.
* Heading weight should be decided by its importance on the page and not how big it should look, as the heading tag chosen affects the order the headings are listed on screen readers.
* Use HTML5 semantic tags like `<main>`, `<nav>`, `<header>`, `<aside>`, `<article>`, `<section>`, `<footer>` to indicate landmarks on the page.
## ARIA
- Express semantics that HTML can't express on its own.
- Accessibility tree = DOM + ARIA.
- ARIA attributes
- Allow us to modify the accessibility tree before they are exposed to assistive technologies.
- DO NOT modify the element appearance.
- DO NOT modify element behaviour.
- DO NOT add focusability.
- DO NOT add keyboard event handling.
- E.g. for custom checkboxes, adding ARIA attributes is not sufficient, you will need to write your own JavaScript to emulate the native behaviour to synchronize the ARIA attributes and values with the actual visual state, such as toggling using clicks and hitting spacebar. It's probably not worth it to reinvent the wheel by writing your own custom widgets that already exist in HTML5.
- ARIA can add semantics to elements that have no native semantics, such as `<div>`. ARIA can also modify element semantics.
- ARIA allows developers to create accessible widgets that do not exist in HTML5, such as a tree widget.
- `aria-role` attributes tell assistive technologies that the element should follow that role's accessibility patterns. There are well-defined roles in the HTML spec. Do not define them on your own.
- `tabindex="0"` is usually added to it elements that have `role` added so that it can be focused.
- Assistive labelling
- `aria-label` is useful for labelling buttons where the content is empty or contains only icons.
- `aria-labelledby` is similar to `<label>` elements, and can be used on any elements.
* Express semantics that HTML can't express on its own.
* Accessibility tree = DOM + ARIA.
* ARIA attributes
* Allow us to modify the accessibility tree before they are exposed to assistive technologies.
* DO NOT modify the element appearance.
* DO NOT modify element behaviour.
* DO NOT add focusability.
* DO NOT add keyboard event handling.
* E.g. for custom checkboxes, adding ARIA attributes is not sufficient, you will need to write your own JavaScript to emulate the native behaviour to synchronize the ARIA attributes and values with the actual visual state, such as toggling using clicks and hitting spacebar. It's probably not worth it to reinvent the wheel by writing your own custom widgets that already exist in HTML5.
* ARIA can add semantics to elements that have no native semantics, such as `<div>`. ARIA can also modify element semantics.
* ARIA allows developers to create accessible widgets that do not exist in HTML5, such as a tree widget.
* `aria-role` attributes tell assistive technologies that the element should follow that role's accessibility patterns. There are well-defined roles in the HTML spec. Do not define them on your own.
* `tabindex="0"` is usually added to it elements that have `role` added so that it can be focused.
* Assistive labelling
* `aria-label` is useful for labelling buttons where the content is empty or contains only icons.
* `aria-labelledby` is similar to `<label>` elements, and can be used on any elements.
```html
/* Normal label example */
<input type="radio" id="coffee-label">
@ -88,15 +89,16 @@ The following is a checklist that contains recommendations for implementing HTML
<div role="radio" aria-labelledby="coffee-label"></div>
<span id="coffee-label">Coffee</span>
```
- ARIA Relationships
- ARIA relationship attributes create semantic relationships between elements on the page. The `aria-labelledby` attribute in the previous example indicates that the `<div>` is labelled by the element with that `id`.
- Possible relationship attributes include `aria-activedescendent`, `aria-describedby`, `aria-labelledby`, `aria-owns`, `aria-posinset` and `aria-setsize`.
- With ARIA, you can expose only relevant parts of the page to accessibility tree. Elements can be hidden via:
- Setting `visibility`: `<button style="visibility: hidden">`.
- Setting `display`: `<button style="display: none">`.
- HTML5 `hidden` attribute: `<span hidden>`. This makes the element hidden to everyone.
- `aria-hidden` attribute: `<div aria-hidden="true">`. This makes the element hidden to screenreaders too. Note that `aria-hidden` attribute requires an explicit value of `true` or `false`.
- Technique for screenreader-only text:
* ARIA Relationships
* ARIA relationship attributes create semantic relationships between elements on the page. The `aria-labelledby` attribute in the previous example indicates that the `<div>` is labelled by the element with that `id`.
* Possible relationship attributes include `aria-activedescendent`, `aria-describedby`, `aria-labelledby`, `aria-owns`, `aria-posinset` and `aria-setsize`.
* With ARIA, you can expose only relevant parts of the page to accessibility tree. Elements can be hidden via:
* Setting `visibility`: `<button style="visibility: hidden">`.
* Setting `display`: `<button style="display: none">`.
* HTML5 `hidden` attribute: `<span hidden>`. This makes the element hidden to everyone.
* `aria-hidden` attribute: `<div aria-hidden="true">`. This makes the element hidden to screenreaders too. Note that `aria-hidden` attribute requires an explicit value of `true` or `false`.
* Technique for screenreader-only text:
```
.screenreader {
position: absolute;
@ -106,31 +108,31 @@ The following is a checklist that contains recommendations for implementing HTML
overflow: hidden;
}
```
- `aria-live` attribute can be used to grab the assistive technology's attention to cause it to announce updates to the user. Practically, include `aria-live` attributes in the initial page load. The different `aria-live` values include:
- `off` (default) - Updates will not be presented unless the region is currently focused.
- `polite` - Assistive technologies should announce updates at the next graceful opportunity, such as at the end of speaking the current sentence on when the user pauses typing. Such as receiving new chat messages.
- `assertive` - Highest priority and assistive technologies should notify the user immediately. Examples include server status error alerts.
- `aria-atomic` attribute indicates whether the entire region should be presented as a whole when communicating updates. Such as a date widget comprising of multiple `<input>` fields for day/month/year. When the user changes a field, the full contents of the widget will be read out. It takes in a `true` or `false` value.
- `aria-relevant` attribute indicates what types of changes should be presented to the user.
- `additions` - Element nodes are added to the DOM within the live region.
- `removals` - Text or element nodes within the live region are removed from the DOM.
- `text` - Text is added to any DOM descendant nodes of the live region.
- `all` - Equivalent to the combination of all values, `additions removals text`.
- `additions text` (default) - Equivalent to the combination of values, `additions text`.
- `aria-busy` attribute indicates the assistive technologies should ignore changes to the element, such as when things are loading, for example after a temporary connectivity loss. It takes in `true` or `false`. It takes in a `true` or `false` value.
* `aria-live` attribute can be used to grab the assistive technology's attention to cause it to announce updates to the user. Practically, include `aria-live` attributes in the initial page load. The different `aria-live` values include:
* `off` (default) - Updates will not be presented unless the region is currently focused.
* `polite` - Assistive technologies should announce updates at the next graceful opportunity, such as at the end of speaking the current sentence on when the user pauses typing. Such as receiving new chat messages.
* `assertive` - Highest priority and assistive technologies should notify the user immediately. Examples include server status error alerts.
* `aria-atomic` attribute indicates whether the entire region should be presented as a whole when communicating updates. Such as a date widget comprising of multiple `<input>` fields for day/month/year. When the user changes a field, the full contents of the widget will be read out. It takes in a `true` or `false` value.
* `aria-relevant` attribute indicates what types of changes should be presented to the user.
* `additions` - Element nodes are added to the DOM within the live region.
* `removals` - Text or element nodes within the live region are removed from the DOM.
* `text` - Text is added to any DOM descendant nodes of the live region.
* `all` - Equivalent to the combination of all values, `additions removals text`.
* `additions text` (default) - Equivalent to the combination of values, `additions text`.
* `aria-busy` attribute indicates the assistive technologies should ignore changes to the element, such as when things are loading, for example after a temporary connectivity loss. It takes in `true` or `false`. It takes in a `true` or `false` value.
## Style
#### Introduction
- Ensure elements are styled to support the existing accessibility work, such as adding styles for `:focus` and the various ARIA states.
- Flexible user interface that can handle being zoomed or scaled up, for users who have trouble reading smaller text.
- Color choices and the importance of contrast, making sure we are not conveying information just with color alone.
* Ensure elements are styled to support the existing accessibility work, such as adding styles for `:focus` and the various ARIA states.
* Flexible user interface that can handle being zoomed or scaled up, for users who have trouble reading smaller text.
* Color choices and the importance of contrast, making sure we are not conveying information just with color alone.
#### Focus
- As much as possible, leave the default focus in place. Do not remove the `:focus` styling just because it does not fit into your design or looks odd! - A good technique is to use a similar styling as `:hover` for `:focus`.
- Some CSS resets would kill off the focus styling, so it's important to be aware of them and get them back.
* As much as possible, leave the default focus in place. Do not remove the `:focus` styling just because it does not fit into your design or looks odd! - A good technique is to use a similar styling as `:hover` for `:focus`.
* Some CSS resets would kill off the focus styling, so it's important to be aware of them and get them back.
#### Styling with ARIA
@ -172,9 +174,9 @@ Use a meta viewport tag:
Use relative units like `%`, `em` and `rem`. The differences are as follows:
- `%` - Relative to the containing block.
- `em` - Relative to the `font-size` of the parent.
- `rem` - Relative to the `font-size` of the root, which is the `<html>` element.
* `%` - Relative to the containing block.
* `em` - Relative to the `font-size` of the parent.
* `rem` - Relative to the `font-size` of the root, which is the `<html>` element.
Interactive interface elements such as buttons should be large enough, have enough spacing around itself so that they do not overlap with other interactive elements.
@ -192,10 +194,10 @@ Some users might be using a High Contrast mode which allows a user to invert the
Fixing accessibility issues is like fixing bugs; it is best looked at through the lens of impact. How can you have the most impact on users with the least amount of effort?
- How frequent is this piece of UI used? Is it part of a critical flow?
- How badly does this accessibility issue affect your users?
- How expensive is it going to cost to fix?
* How frequent is this piece of UI used? Is it part of a critical flow?
* How badly does this accessibility issue affect your users?
* How expensive is it going to cost to fix?
###### References
- https://www.udacity.com/course/web-accessibility--ud891
* https://www.udacity.com/course/web-accessibility--ud891

@ -1,41 +1,49 @@
Browser
==
# Browser
## Glossary
- **BOM** - The Browser Object Model (BOM) is a browser-specific convention referring to all the objects exposed by the web browser. The `window` object is one of them.
- **CSSOM** - CSS Object Model.
- **DOM** - The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML, and XML documents.
- **Reflow** - When the changes affect document contents or structure, or element position, a reflow (or relayout) happens.
- **Repaint** - When changing element styles which don't affect the element's position on a page (such as `background-color`, `border-color`, `visibility`), the browser just repaints the element again with the new styles applied (that means a "repaint" or "restyle" is happening).
- **Composite** - TODO
* **BOM** - The Browser Object Model (BOM) is a browser-specific convention referring to all the objects exposed by the web browser. The `window` object is one of them.
* **CSSOM** - CSS Object Model.
* **DOM** - The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML, and XML documents.
* **Reflow** - When the changes affect document contents or structure, or element position, a reflow (or relayout) happens.
* **Repaint** - When changing element styles which don't affect the element's position on a page (such as `background-color`, `border-color`, `visibility`), the browser just repaints the element again with the new styles applied (that means a "repaint" or "restyle" is happening).
* **Composite** - TODO
## Rendering
High level flow of how browsers render a webpage:
1. DOM
- The DOM (Document Object Model) is formed from the HTML that is received from a server.
- Characters -> Tokens -> Nodes -> DOM.
- DOM construction is incremental.
- CSS and JS are requested as the respective `<link>` and `<script>` tags are encountered.
* The DOM (Document Object Model) is formed from the HTML that is received from a server.
* Characters -> Tokens -> Nodes -> DOM.
* DOM construction is incremental.
* CSS and JS are requested as the respective `<link>` and `<script>` tags are encountered.
1. CSSOM
- Styles are loaded and parsed, forming the CSSOM (CSS Object Model).
- Characters -> Tokens -> Nodes -> CSSOM.
- CSSOM construction is not incremental.
- Browser blocks page rendering until it receives and processes all the CSS.
- CSS is render blocking.
* Styles are loaded and parsed, forming the CSSOM (CSS Object Model).
* Characters -> Tokens -> Nodes -> CSSOM.
* CSSOM construction is not incremental.
* Browser blocks page rendering until it receives and processes all the CSS.
* CSS is render blocking.
1. Render Tree
- On top of DOM and CSSOM, a render tree is created, which is a set of objects to be rendered. Render tree reflects the DOM structure except for invisible elements (like the <head> tag or elements that have `display: none`; set). Each text string is represented in the rendering tree as a separate renderer. Each of the rendering objects contains its corresponding DOM object (or a text block) plus the calculated styles. In other words, the render tree describes the visual representation of a DOM.
* On top of DOM and CSSOM, a render tree is created, which is a set of objects to be rendered. Render tree reflects the DOM structure except for invisible elements (like the <head> tag or elements that have `display: none`; set). Each text string is represented in the rendering tree as a separate renderer. Each of the rendering objects contains its corresponding DOM object (or a text block) plus the calculated styles. In other words, the render tree describes the visual representation of a DOM.
1. Layout
- For each render tree element, its coordinates are calculated, which is called "layout". Browsers use a flow method which only required one pass to layout all the elements (tables require more than one pass).
* For each render tree element, its coordinates are calculated, which is called "layout". Browsers use a flow method which only required one pass to layout all the elements (tables require more than one pass).
1. Painting
- Finally, this gets actually displayed in a browser window, a process called "painting".
* Finally, this gets actually displayed in a browser window, a process called "painting".
###### References
- http://taligarsiel.com/Projects/howbrowserswork1.htm
- https://medium.freecodecamp.org/its-not-dark-magic-pulling-back-the-curtains-from-your-stylesheets-c8d677fa21b2
* http://taligarsiel.com/Projects/howbrowserswork1.htm
* https://medium.freecodecamp.org/its-not-dark-magic-pulling-back-the-curtains-from-your-stylesheets-c8d677fa21b2
## Repaint
@ -44,16 +52,17 @@ When changing element styles which don't affect the element's position on a page
## Reflow
When the changes affect document contents or structure, or element position, a reflow (or relayout) happens. These changes are usually triggered by:
- DOM manipulation (element addition, deletion, altering, or changing element order)
- Contents changes, including text changes in form fields
- Calculation or altering of CSS properties
- Adding or removing style sheets
- Changing the "class" attribute
- Browser window manipulation (resizing, scrolling); Pseudo-class activation (`:hover`)
* DOM manipulation (element addition, deletion, altering, or changing element order)
* Contents changes, including text changes in form fields
* Calculation or altering of CSS properties
* Adding or removing style sheets
* Changing the "class" attribute
* Browser window manipulation (resizing, scrolling); Pseudo-class activation (`:hover`)
#### References
- [How Browsers Work](http://taligarsiel.com/Projects/howbrowserswork1.htm)
- [What Every Frontend Developer Should Know About Webpage Rendering](http://frontendbabel.info/articles/webpage-rendering-101/)
- [Rendering: repaint, reflow/relayout, restyle](http://www.phpied.com/rendering-repaint-reflowrelayout-restyle/)
- [Building the DOM faster: speculative parsing, async, defer and preload](https://hacks.mozilla.org/2017/09/building-the-dom-faster-speculative-parsing-async-defer-and-preload/)
* [How Browsers Work](http://taligarsiel.com/Projects/howbrowserswork1.htm)
* [What Every Frontend Developer Should Know About Webpage Rendering](http://frontendbabel.info/articles/webpage-rendering-101/)
* [Rendering: repaint, reflow/relayout, restyle](http://www.phpied.com/rendering-repaint-reflowrelayout-restyle/)
* [Building the DOM faster: speculative parsing, async, defer and preload](https://hacks.mozilla.org/2017/09/building-the-dom-faster-speculative-parsing-async-defer-and-preload/)

@ -1,14 +1,13 @@
Caching
==
# Caching
WIP.
## Glossary
- **Cookies**
* **Cookies**
#### References
- [A Tale of Four Caches](https://calendar.perfplanet.com/2016/a-tale-of-four-caches/)
- [Web Caching Basics: Terminology, HTTP Headers, and Caching Strategies](https://www.digitalocean.com/community/tutorials/web-caching-basics-terminology-http-headers-and-caching-strategies)
- [This browser tweak saved 60% of requests to Facebook](https://code.facebook.com/posts/557147474482256/this-browser-tweak-saved-60-of-requests-to-facebook/)
* [A Tale of Four Caches](https://calendar.perfplanet.com/2016/a-tale-of-four-caches/)
* [Web Caching Basics: Terminology, HTTP Headers, and Caching Strategies](https://www.digitalocean.com/community/tutorials/web-caching-basics-terminology-http-headers-and-caching-strategies)
* [This browser tweak saved 60% of requests to Facebook](https://code.facebook.com/posts/557147474482256/this-browser-tweak-saved-60-of-requests-to-facebook/)

@ -1,5 +1,4 @@
CSS
==
# CSS
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.
@ -11,19 +10,19 @@ If you are a total beginner to CSS, Codecademy's [HTML & CSS course](https://www
## Glossary
- [**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.
- [**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.
- 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.
- Typically used in type selectors/pseduo elements (`h1`, `div`, `:before`), class/attribute selectors (`.btn`, `[type="radio"]`), pseudo-classes (`:hover`) and ID selectors (`#someElement`).
- Inline styles added to an element always overwrite any styles in external stylesheets, and thus can be thought of as having the highest specificity.
- 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).
- [**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.
- Initial value: `static`
- Values that are frequently used: `relative`, `absolute`, `fixed`, `sticky`
- [**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`.
- Initial value: `none`
- Values that are frequently used: `left`, `right`, `inline-start`, `inline-end`.
- 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
* [**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.
* [**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.
* 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.
* Typically used in type selectors/pseduo elements (`h1`, `div`, `:before`), class/attribute selectors (`.btn`, `[type="radio"]`), pseudo-classes (`:hover`) and ID selectors (`#someElement`).
* Inline styles added to an element always overwrite any styles in external stylesheets, and thus can be thought of as having the highest specificity.
* 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).
* [**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.
* Initial value: `static`
* Values that are frequently used: `relative`, `absolute`, `fixed`, `sticky`
* [**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`.
* Initial value: `none`
* Values that are frequently used: `left`, `right`, `inline-start`, `inline-end`.
* 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
## Writing CSS without Side Effects
@ -31,4 +30,4 @@ TODO
###### References
- https://philipwalton.com/articles/side-effects-in-css/
* https://philipwalton.com/articles/side-effects-in-css/

@ -1,14 +1,14 @@
Design Questions
==
# Design Questions
## Autocomplete Widget
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.
- How would you design a frontend to support the following features:
- Fetch data from a backend API
- Render results as a tree (items can have parents/children - it's not just a flat list)
- Support for checkbox, radio button, icon, and regular list items - items come in many forms
- What does the component's API look like?
- What does the backend API look like?
- 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)?
- 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?
* How would you design a frontend to support the following features:
* Fetch data from a backend API
* Render results as a tree (items can have parents/children - it's not just a flat list)
* Support for checkbox, radio button, icon, and regular list items - items come in many forms
* What does the component's API look like?
* What does the backend API look like?
* 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)?
* 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?

@ -1,9 +1,8 @@
DOM
==
# DOM
## Glossary
- **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.
* **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.
## Node API
@ -11,25 +10,25 @@ Here's a list of the essential and more common DOM `Node` APIs. It is important
**Properties**
- `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.
- `Node.firstChild`
- `Node.lastChild`
- `Node.nextSibling` - Returns a `Node` representing the next node in the tree, or `null` if there isn't such a node.
- `Node.nodeName` - `DIV`, `SPAN`, etc. Note that it is in upper case in HTML documents, and has the same value as `Element.tagName`.
- `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`.
- `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`.
- `Node.previousSibling` - Returns a `Node` representing the previous node in the tree, or `null` if there isn't such a node.
- `Node.textContent` - Returns / Sets the textual content of an element and all its descendants.
* `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.
* `Node.firstChild`
* `Node.lastChild`
* `Node.nextSibling` - Returns a `Node` representing the next node in the tree, or `null` if there isn't such a node.
* `Node.nodeName` - `DIV`, `SPAN`, etc. Note that it is in upper case in HTML documents, and has the same value as `Element.tagName`.
* `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`.
* `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`.
* `Node.previousSibling` - Returns a `Node` representing the previous node in the tree, or `null` if there isn't such a node.
* `Node.textContent` - Returns / Sets the textual content of an element and all its descendants.
**Methods**
- `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.
- `Node.cloneNode(node)` - Clone a `Node`, and optionally, all of its contents. By default, it clones the content of the node.
- `Node.contains(node)` - Returns a `Boolean` value indicating whether a node is a descendant of a given node or not.
- `Node.hasChildNodes()` - Returns a `Boolean` indicating if the element has any child nodes, or not.
- `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.
- `Node.removeChild(node)` - Removes a child node from the current element, which must be a child of the current node.
- `Node.replaceChild(newChild, oldChild)` - Replaces one child node of the specified node with another node.
* `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.
* `Node.cloneNode(node)` - Clone a `Node`, and optionally, all of its contents. By default, it clones the content of the node.
* `Node.contains(node)` - Returns a `Boolean` value indicating whether a node is a descendant of a given node or not.
* `Node.hasChildNodes()` - Returns a `Boolean` indicating if the element has any child nodes, or not.
* `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.
* `Node.removeChild(node)` - Removes a child node from the current element, which must be a child of the current node.
* `Node.replaceChild(newChild, oldChild)` - Replaces one child node of the specified node with another node.
## Element API
@ -37,42 +36,42 @@ Here's a list of the essential and more common DOM `Element` APIs. It is importa
**Properties**
- `Element.attributes` - Returns a `NamedNodeMap` object containing the assigned attributes of the corresponding HTML element.
- `Element.classList` - Returns a `DOMTokenList` containing the list of class attributes.
- `DOMTokenList.add(String [, String])` - Add specified class values. If these classes already exist in attribute of the element, they are ignored.
- `DOMTokenList.remove(String [, String])` - Remove specified class values.
- `DOMTokenList.toggle(String [, force])` - Toggle specified class value. If second argument is present and evaluates to `true`, add the class value, else remove it.
- `DOMTokenList.contains(String)` - Checks if specified class value exists in class attribute of the element.
- `Element.className` - A `DOMString` representing the class of the element.
- `Element.id`
- `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.
- `Element.tagName` - `DIV`, `SPAN`, etc. Note that it is in upper case in HTML documents, and has the same value as `Node.nodeName`.
* `Element.attributes` - Returns a `NamedNodeMap` object containing the assigned attributes of the corresponding HTML element.
* `Element.classList` - Returns a `DOMTokenList` containing the list of class attributes.
* `DOMTokenList.add(String [, String])` - Add specified class values. If these classes already exist in attribute of the element, they are ignored.
* `DOMTokenList.remove(String [, String])` - Remove specified class values.
* `DOMTokenList.toggle(String [, force])` - Toggle specified class value. If second argument is present and evaluates to `true`, add the class value, else remove it.
* `DOMTokenList.contains(String)` - Checks if specified class value exists in class attribute of the element.
* `Element.className` - A `DOMString` representing the class of the element.
* `Element.id`
* `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.
* `Element.tagName` - `DIV`, `SPAN`, etc. Note that it is in upper case in HTML documents, and has the same value as `Node.nodeName`.
**Methods**
- `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).
- `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).
- `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`.
- `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.
- `Element.getElementsByTagName(tagName)` - Returns a live `HTMLCollection` containing all descendant elements, of a particular tag name, from the current element.
- `Element.querySelector(selectors)` - Returns the first `Node` which matches the specified selector string relative to the element.
- `Element.querySelectorAll(selectors)` - Returns a `NodeList` of nodes which match the specified selector string relative to the element.
- `ChildNode.remove()` - Removes the element from the children list of its parent. TODO: Check whether it's `Element` or `ChildNode`.
- `Element.setAttribute(attrName, value)` - Sets the value of a named attribute of the current node.
- `Element.removeAttribute(attrName)` - Removes the named attribute from the current node.
* `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).
* `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).
* `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`.
* `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.
* `Element.getElementsByTagName(tagName)` - Returns a live `HTMLCollection` containing all descendant elements, of a particular tag name, from the current element.
* `Element.querySelector(selectors)` - Returns the first `Node` which matches the specified selector string relative to the element.
* `Element.querySelectorAll(selectors)` - Returns a `NodeList` of nodes which match the specified selector string relative to the element.
* `ChildNode.remove()` - Removes the element from the children list of its parent. TODO: Check whether it's `Element` or `ChildNode`.
* `Element.setAttribute(attrName, value)` - Sets the value of a named attribute of the current node.
* `Element.removeAttribute(attrName)` - Removes the named attribute from the current node.
## Document API
- `document.getElementById(id)` - An Element object, or null if an element with the specified ID is not in the document.
* `document.getElementById(id)` - An Element object, or null if an element with the specified ID is not in the document.
## Window/Document Events
- `document.addEventListener('DOMContentLoaded', callback)`
- 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.
- This corresponds to `document.readyState === 'interactive'`.
- `window.onload = function() {}`
- `window`'s `load` event is only fired after the DOM and all assets have loaded.
- This corresponds to `document.readyState === 'complete'`.
* `document.addEventListener('DOMContentLoaded', callback)`
* 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.
* This corresponds to `document.readyState === 'interactive'`.
* `window.onload = function() {}`
* `window`'s `load` event is only fired after the DOM and all assets have loaded.
* This corresponds to `document.readyState === 'complete'`.
## Questions
@ -98,5 +97,5 @@ const divArray3 = [...nodeList];
## References
- https://developer.mozilla.org/en-US/docs/Web/API/Node
- https://developer.mozilla.org/en-US/docs/Web/API/Element
* https://developer.mozilla.org/en-US/docs/Web/API/Node
* https://developer.mozilla.org/en-US/docs/Web/API/Element

@ -1,11 +1,10 @@
HTML
==
# HTML
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.
## Glossary
- **Doctype**
* **Doctype**
## Deprecated Tags
@ -13,6 +12,6 @@ There are a number of tags from past versions of HTML that have become deprecate
## Script Loading
- `<script>` - HTML parsing is blocked, the script is fetched and executed immediately, HTML parsing resumes after the script is executed.
- `<script async>` - The script will be fetched in parallel to HTML parsing and executed as soon as it is available (potentially before HTML parsing completes). Use `async` when the script is independent of any other scripts on the page, for example analytics.
- `<script defer>` - The script will be fetched in parallel to HTML parsing and executed when the page has finished parsing. If there are multiple of them, each deferred script is executed in the order they were encoun­tered in the document.
* `<script>` - HTML parsing is blocked, the script is fetched and executed immediately, HTML parsing resumes after the script is executed.
* `<script async>` - The script will be fetched in parallel to HTML parsing and executed as soon as it is available (potentially before HTML parsing completes). Use `async` when the script is independent of any other scripts on the page, for example analytics.
* `<script defer>` - The script will be fetched in parallel to HTML parsing and executed when the page has finished parsing. If there are multiple of them, each deferred script is executed in the order they were encoun­tered in the document.

File diff suppressed because it is too large Load Diff

@ -1,75 +1,74 @@
JavaScript
==
# JavaScript
WIP.
## Contents
- [Glossary](#glossary)
- [Core Language](#core-language)
- [Design Patterns](#design-patterns)
- [Strict Mode](#strict-mode)
* [Glossary](#glossary)
* [Core Language](#core-language)
* [Design Patterns](#design-patterns)
* [Strict Mode](#strict-mode)
## Glossary
- **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)
- **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.
- **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)
- **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)
- Promises can contain an immediate value.
- **Prototype** - TBD
- **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.
* **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)
* **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.
* **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)
* **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)
* Promises can contain an immediate value.
* **Prototype** - TBD
* **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.
## Core Language
### Variables
- Reference: [Types and Grammar](https://github.com/getify/You-Dont-Know-JS/blob/master/types%20%26%20grammar/ch1.md)
- Types
- Scopes
- [Coercion](https://github.com/getify/You-Dont-Know-JS/blob/master/up%20%26%20going/ch2.md#coercion)
* Reference: [Types and Grammar](https://github.com/getify/You-Dont-Know-JS/blob/master/types%20%26%20grammar/ch1.md)
* Types
* Scopes
* [Coercion](https://github.com/getify/You-Dont-Know-JS/blob/master/up%20%26%20going/ch2.md#coercion)
### Functions
- Reference: [this & Object Prototypes](https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch3.md)
- Declaration vs Expression
- Closures
- `.call`, `.apply` and `.bind`
- Currying
- Arrow functions and lexical this
* Reference: [this & Object Prototypes](https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch3.md)
* Declaration vs Expression
* Closures
* `.call`, `.apply` and `.bind`
* Currying
* Arrow functions and lexical this
### Prototypes and Objects
- 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)
- Prototype chain
- `this` keyword
- https://rainsoft.io/gentle-explanation-of-this-in-javascript/
- https://codeburst.io/the-simple-rules-to-this-in-javascript-35d97f31bde3
- Classes
- Methods
- 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.
* 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)
* Prototype chain
* `this` keyword
* https://rainsoft.io/gentle-explanation-of-this-in-javascript/
* https://codeburst.io/the-simple-rules-to-this-in-javascript-35d97f31bde3
* Classes
* Methods
* 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.
### Async
- 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)
- `setTimeout`, `setInterval` and event loop
- [setImmediate() vs nextTick() vs setTimeout(fn,0)](http://voidcanvas.com/setimmediate-vs-nexttick-vs-settimeout/)
- Event Loop
- Debounce and Throttle
- Throttling enforces a maximum number of times a function can be called over time.
- Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called.
- https://css-tricks.com/debouncing-throttling-explained-examples/
- Callbacks
- [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
- [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
* 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)
* `setTimeout`, `setInterval` and event loop
* [setImmediate() vs nextTick() vs setTimeout(fn,0)](http://voidcanvas.com/setimmediate-vs-nexttick-vs-settimeout/)
* Event Loop
* Debounce and Throttle
* Throttling enforces a maximum number of times a function can be called over time.
* Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called.
* https://css-tricks.com/debouncing-throttling-explained-examples/
* Callbacks
* [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
* [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
**Reference**
- https://www.vikingcodeschool.com/falling-in-love-with-javascript/the-javascript-event-loop
* https://www.vikingcodeschool.com/falling-in-love-with-javascript/the-javascript-event-loop
## Design Patterns
- https://addyosmani.com/resources/essentialjsdesignpatterns/book/
* https://addyosmani.com/resources/essentialjsdesignpatterns/book/
## Strict Mode
@ -79,30 +78,30 @@ WIP.
**Converting Mistakes into Errors**
- Prevent accidental creation of global variables.
- Makes assignments which would otherwise silently fail throw an exception.
- Makes attempts to delete undeletable properties throw errors.
- Requires that all properties named in an object literal be unique. Duplicate property names are a syntax error in strict mode.
- Requires that function parameter names be unique. In normal code the last duplicated argument hides previous identically-named arguments.
- 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.
* Prevent accidental creation of global variables.
* Makes assignments which would otherwise silently fail throw an exception.
* Makes attempts to delete undeletable properties throw errors.
* Requires that all properties named in an object literal be unique. Duplicate property names are a syntax error in strict mode.
* Requires that function parameter names be unique. In normal code the last duplicated argument hides previous identically-named arguments.
* 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.
**Simplifying Variable Uses**
- Prohibits `with`.
- `eval` of strict mode code does not introduce new variables into the surrounding scope.
- Forbids deleting plain variables. `delete` name in strict mode is a syntax error: `var x; delete x; // !!! syntax error`.
* Prohibits `with`.
* `eval` of strict mode code does not introduce new variables into the surrounding scope.
* Forbids deleting plain variables. `delete` name in strict mode is a syntax error: `var x; delete x; // !!! syntax error`.
**Paving the way for future ECMAScript versions**
- 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.
- 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.
- Second, strict mode prohibits function statements not at the top level of a script or function.
* 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.
* 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.
* Second, strict mode prohibits function statements not at the top level of a script or function.
## Transpilation: TBD
## Useful Links
- https://medium.com/javascript-scene/10-interview-questions-every-javascript-developer-should-know-6fa6bdf5ad95#.l2n8icwl4
- https://github.com/mbeaudru/modern-js-cheatsheet
- [Functional Programming in Javascript - Javascript Allonge](https://leanpub.com/javascriptallongesix/read)
- [Dr. Frisby's Mostly Adequate Guide to Functional Programming](https://drboolean.gitbooks.io/mostly-adequate-guide/content/)
* https://medium.com/javascript-scene/10-interview-questions-every-javascript-developer-should-know-6fa6bdf5ad95#.l2n8icwl4
* https://github.com/mbeaudru/modern-js-cheatsheet
* [Functional Programming in Javascript - Javascript Allonge](https://leanpub.com/javascriptallongesix/read)
* [Dr. Frisby's Mostly Adequate Guide to Functional Programming](https://drboolean.gitbooks.io/mostly-adequate-guide/content/)

@ -1,11 +1,10 @@
Networking
==
# Networking
WIP.
## Glossary
- **JSON**
- **RPC**
- **HTTP**
- **HTTP/2**
* **JSON**
* **RPC**
* **HTTP**
* **HTTP/2**

@ -1,12 +1,11 @@
Performance
==
# Performance
WIP.
## Glossary
- **Critical Rendering Path** -
- `requestAnimationFrame`
* **Critical Rendering Path** -
* `requestAnimationFrame`
## General Strategies
@ -16,51 +15,51 @@ WIP.
## Loading
- Minify, Compress, Cache assets.
- 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.
* Minify, Compress, Cache assets.
* 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.
## Rendering
- Remove whitespace and comments from HTML/CSS/JS file via minification.
- CSS
- CSS blocks rendering AND JavaScript execution.
- Split up CSS for fewer rendering blocking CSS stylesheets by using media attributes.
- Download only the necessary CSS before the browser can start to render.
- https://developers.google.com/web/fundamentals/design-and-ui/responsive/#css-media-queries
- Use Simpler selectors.
- JavaScript
- JS blocks HTML parsing. If the script is external, it will have to be downloaded first. This incurs latency in network and execution.
- Shift `<script>` tags to the bottom.
- Async:
- Scripts that don't modify the DOM or CSSOM can use the `async` attribute to tell the browser not to block DOM parsing and does not need to wait for the CSSOM to be ready.
- Defer JavaScript execution:
- There is also a `defer` attribute available. The difference is that with `defer`, the script waits to execute until after the document has been parsed, whereas `async` lets the script run in the background while the document is being parsed.
- Use web workers for long running operations to move into a web worker thread.
- Use `requestAnimationFrame`
* Remove whitespace and comments from HTML/CSS/JS file via minification.
* CSS
* CSS blocks rendering AND JavaScript execution.
* Split up CSS for fewer rendering blocking CSS stylesheets by using media attributes.
* Download only the necessary CSS before the browser can start to render.
* https://developers.google.com/web/fundamentals/design-and-ui/responsive/#css-media-queries
* Use Simpler selectors.
* JavaScript
* JS blocks HTML parsing. If the script is external, it will have to be downloaded first. This incurs latency in network and execution.
* Shift `<script>` tags to the bottom.
* Async:
* Scripts that don't modify the DOM or CSSOM can use the `async` attribute to tell the browser not to block DOM parsing and does not need to wait for the CSSOM to be ready.
* Defer JavaScript execution:
* There is also a `defer` attribute available. The difference is that with `defer`, the script waits to execute until after the document has been parsed, whereas `async` lets the script run in the background while the document is being parsed.
* Use web workers for long running operations to move into a web worker thread.
* Use `requestAnimationFrame`
###### References
- https://bitsofco.de/understanding-the-critical-rendering-path/
* https://bitsofco.de/understanding-the-critical-rendering-path/
## Measuring
- [Navigation Timing API](https://developer.mozilla.org/en/docs/Web/API/Navigation_timing_API) is a JavaScript API for accurately measuring performance on the web. The API provides a simple way to get accurate and detailed timing statistics natively for page navigation and load events.
- `performance.timing`: An object with the timestamps of the various events on the page. Some uses:
- Network latency: `responseEnd` - `fetchStart`.
- The time taken for page load once the page is received from the server: `loadEventEnd` - `responseEnd`.
- The whole process of navigation and page load: `loadEventEnd` - `navigationStart`.
* [Navigation Timing API](https://developer.mozilla.org/en/docs/Web/API/Navigation_timing_API) is a JavaScript API for accurately measuring performance on the web. The API provides a simple way to get accurate and detailed timing statistics natively for page navigation and load events.
* `performance.timing`: An object with the timestamps of the various events on the page. Some uses:
* Network latency: `responseEnd` - `fetchStart`.
* The time taken for page load once the page is received from the server: `loadEventEnd` - `responseEnd`.
* The whole process of navigation and page load: `loadEventEnd` - `navigationStart`.
## Tools
- Yahoo YSlow
- Google PageSpeed Insights
- WebPageTest
- Sitespeed.io
- Google Lighthouse
* Yahoo YSlow
* Google PageSpeed Insights
* WebPageTest
* Sitespeed.io
* Google Lighthouse
## Web Performance Rules
- https://developers.google.com/web/fundamentals/performance/critical-rendering-path/measure-crp
- http://stevesouders.com/hpws/rules.php
- https://developer.yahoo.com/performance/rules.html
- https://browserdiet.com/en/
* https://developers.google.com/web/fundamentals/performance/critical-rendering-path/measure-crp
* http://stevesouders.com/hpws/rules.php
* https://developer.yahoo.com/performance/rules.html
* https://browserdiet.com/en/

@ -1,11 +1,10 @@
Security
==
# Security
## Glossary
- **CORS** - Cross-Origin Resource Sharing (CORS).
- **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.
- **XSS** - Cross-site scripting (XSS).
* **CORS** - Cross-Origin Resource Sharing (CORS).
* **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.
* **XSS** - Cross-site scripting (XSS).
## CORS
@ -21,38 +20,38 @@ XSS vulnerabilities allow attackers to bypass essentially all CSRF preventions.
#### Protection
- Verifying Same Origin with Standard Headers
- There are two steps to this check:
* Verifying Same Origin with Standard Headers
* There are two steps to this check:
1. Determining the origin the request is coming from (source origin).
2. Determining the origin the request is going to (target origin).
- Examine the `Origin`, `Referer` and `Host` Header values.
- Synchronizer Tokens
- The CSRF token is added as a hidden field for forms or within the URL.
- Characteristics of a CSRF Token
- Unique per user session
- Large random value
- Generated by a cryptographically secure random number generator
- The server rejects the requested action if the CSRF token fails validation.
- Double Cookie
- 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.
- 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 <input> values contains the exact same cookie value. Any difference between the two means a possible XSRF attack.
- Cookie-to-Header Token
- On login, the web application sets a cookie containing a random token that remains the same for the whole user session
- `Set-Cookie: Csrf-token=i8XNjC4b8KVok4uw5RftR38Wgp2BFwql; expires=Thu, 23-Jul-2015 10:25:33 GMT; Max-Age=31449600; Path=/`
- JavaScript operating on the client side reads its value and copies it into a custom HTTP header sent with each transactional request
- `X-Csrf-Token: i8XNjC4b8KVok4uw5RftR38Wgp2BFwql`
- The server validates presence and integrity of the token.
- 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.
- 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.
- Use of Custom Request Headers
- 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`.
- 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.
- Require user interaction
- Require a re-authentication, using a one-time token, or requiring users to complete a captcha.
* Examine the `Origin`, `Referer` and `Host` Header values.
* Synchronizer Tokens
* The CSRF token is added as a hidden field for forms or within the URL.
* Characteristics of a CSRF Token
* Unique per user session
* Large random value
* Generated by a cryptographically secure random number generator
* The server rejects the requested action if the CSRF token fails validation.
* Double Cookie
* 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.
* 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 <input> values contains the exact same cookie value. Any difference between the two means a possible XSRF attack.
* Cookie-to-Header Token
* On login, the web application sets a cookie containing a random token that remains the same for the whole user session
* `Set-Cookie: Csrf-token=i8XNjC4b8KVok4uw5RftR38Wgp2BFwql; expires=Thu, 23-Jul-2015 10:25:33 GMT; Max-Age=31449600; Path=/`
* JavaScript operating on the client side reads its value and copies it into a custom HTTP header sent with each transactional request
* `X-Csrf-Token: i8XNjC4b8KVok4uw5RftR38Wgp2BFwql`
* The server validates presence and integrity of the token.
* 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.
* 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.
* Use of Custom Request Headers
* 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`.
* 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.
* Require user interaction
* Require a re-authentication, using a one-time token, or requiring users to complete a captcha.
###### References
- [OWASP CSRF](https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF))
* [OWASP CSRF](<https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)>)
## HTTPS
@ -75,14 +74,14 @@ HTTPS is HTTP over SSL/TLS. Servers and clients still speak exactly the same HTT
#### Downsides of HTTPS
- TLS handshake computational and latency overhead.
- Encryption and decryption requires more computation power and bandwidth.
* TLS handshake computational and latency overhead.
* Encryption and decryption requires more computation power and bandwidth.
###### References
- https://blog.hartleybrody.com/https-certificates/
- https://github.com/alex/what-happens-when#tls-handshake
- http://robertheaton.com/2014/03/27/how-does-https-actually-work/
* https://blog.hartleybrody.com/https-certificates/
* https://github.com/alex/what-happens-when#tls-handshake
* http://robertheaton.com/2014/03/27/how-does-https-actually-work/
## XSS
@ -97,9 +96,8 @@ http://shebang.brandonmintern.com/foolproof-html-escaping-in-javascript/
## Session hijacking
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies
- https://www.nczonline.net/blog/2009/05/12/cookies-and-security/
* https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies
* https://www.nczonline.net/blog/2009/05/12/cookies-and-security/
## Framebusting

@ -1,5 +1,4 @@
Widgets
==
# Widgets
Here are some commonly seen widgets/components and the considerations we should take into account when designing them.
@ -9,48 +8,48 @@ Also known as typeahead box.
#### UX
- Type a minimum number of characters (typically two) for the results to be displayed. This is because short search terms can result in too many matches and irrelevant results may be returned.
- Number of query suggestions should be kept short and scrollbars should be avoided. Shorter list of results are more manageable and reduces the cognitive load on the user. If you have scrollbars it probably means you are displaying too many results!
- Highlight the non-search terms (suggested terms) in the results. This helps the user differentiate the autocomplete suggestions, make it easier to compare.
- Support keyboard shortcuts: Up/down to navigate and enter to search.
- Show a history of recent searches.
- Use placeholder text in the input field to educate users, such as "Type to view suggestions".
* Type a minimum number of characters (typically two) for the results to be displayed. This is because short search terms can result in too many matches and irrelevant results may be returned.
* Number of query suggestions should be kept short and scrollbars should be avoided. Shorter list of results are more manageable and reduces the cognitive load on the user. If you have scrollbars it probably means you are displaying too many results!
* Highlight the non-search terms (suggested terms) in the results. This helps the user differentiate the autocomplete suggestions, make it easier to compare.
* Support keyboard shortcuts: Up/down to navigate and enter to search.
* Show a history of recent searches.
* Use placeholder text in the input field to educate users, such as "Type to view suggestions".
#### Performance
- Use windowing/virtual lists when the search results is too long.
- Debounce user input and only search when user stops typing for some time (usually 300ms).
* Use windowing/virtual lists when the search results is too long.
* Debounce user input and only search when user stops typing for some time (usually 300ms).
###### References
- https://baymard.com/blog/autocomplete-design
* https://baymard.com/blog/autocomplete-design
### Carousel
#### UX
- Consider preloading a few images to the left/right of the displayed image during idle time so that as the user navigates, he does not have to wait for the image to be downloaded.
- Allow left/right keyboard navigation of the carousel.
* Consider preloading a few images to the left/right of the displayed image during idle time so that as the user navigates, he does not have to wait for the image to be downloaded.
* Allow left/right keyboard navigation of the carousel.
#### Performance
- Lazy load the images. Only load those that the user has a high likelihood of viewing - Current image and a few to the left and right.
* Lazy load the images. Only load those that the user has a high likelihood of viewing - Current image and a few to the left and right.
### Dropdown
- Dropdowns that are displayed on hover are not mobile friendly as there is no hover event on mobile.
- Dropdown positioning can differ based on position of element on screen. If the element is near the edge and the displayed dropdown will be obscured outside of the viewport, the position of the dropdown can and should be changed.
- If the height of the dropdown is too long, it may extend outside of the screen. Be sure to make the dropdown contents scrollable by setting a `max-height`.
* Dropdowns that are displayed on hover are not mobile friendly as there is no hover event on mobile.
* Dropdown positioning can differ based on position of element on screen. If the element is near the edge and the displayed dropdown will be obscured outside of the viewport, the position of the dropdown can and should be changed.
* If the height of the dropdown is too long, it may extend outside of the screen. Be sure to make the dropdown contents scrollable by setting a `max-height`.
### Modal
- Modals can usually be dismissed by clicking on the backdrop. If the user interacts with the modal content by clicking on it, the backdrop might also receive the click event and be dismissed as a result.
* Modals can usually be dismissed by clicking on the backdrop. If the user interacts with the modal content by clicking on it, the backdrop might also receive the click event and be dismissed as a result.
###### References
- https://css-tricks.com/dangers-stopping-event-propagation/
* https://css-tricks.com/dangers-stopping-event-propagation/
### Tooltip
- Tooltips that are displayed on hover are not mobile friendly as there is no hover event on mobile.
- Tooltip positioning can differ based on position of element on screen. If the element is near the edge and the displayed tooltip will be obscured outside of the viewport, the position of the tooltip can and should be changed.
* Tooltips that are displayed on hover are not mobile friendly as there is no hover event on mobile.
* Tooltip positioning can differ based on position of element on screen. If the element is near the edge and the displayed tooltip will be obscured outside of the viewport, the position of the tooltip can and should be changed.

@ -1,5 +1,4 @@
Basics
==
# Basics
## Disclaimer
@ -7,14 +6,13 @@ These items will all change based on your specific company and needs but these i
## Items To Consider
- **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.
- **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.
- **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.
- **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.
- **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 __?")
* **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.
* **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.
* **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.
* **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.
* **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 _\_?")
## Tech Question Technique
- **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.
- **Nitpicking** - Sometimes psuedocode is okay. If testing in C# do you really need the interviewee to write `Console.WriteLine()` or is `Print()` good enough?
-**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?
* **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.
* **Nitpicking** - Sometimes psuedocode is okay. If testing in C# do you really need the interviewee to write `Console.WriteLine()` or is `Print()` good enough? -**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?

@ -1,34 +1,33 @@
Behavioral
==
# Behavioral
Learn the [STAR](https://en.wikipedia.org/wiki/Situation,_task,_action,_result) format. From Wikipedia:
- **Situation** - The interviewer wants you to present a recent challenge and situation in which you found yourself.
- **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.
- **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.
- **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?
* **Situation** - The interviewer wants you to present a recent challenge and situation in which you found yourself.
* **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.
* **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.
* **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?
## General
- Why do you want to work for X company?
- Why do you want to leave your current/last company?
- What are you looking for in your next role?
- Tell me about a time when you had a conflict with a co-worker.
- Tell me about a time in which you had a conflict and needed to influence somebody else.
- What project are you currently working on?
- What is the most challenging aspect of your current project?
- What was the most difficult bug that you fixed in the past 6 months?
- How do you tackle challenges? Name a difficult challenge you faced while working on a project, how you overcame it, and what you learned.
- What are you excited about?
- What frustrates you?
- Imagine it is your first day here at the company. What do you want to work on? What features would you improve on?
- What are the most interesting projects you have worked on and how might they be relevant to this company's environment?
- Tell me about a time you had a disagreement with your manager.
- Talk about a project you are most passionate about, or one where you did your best work.
- What does your best day of work look like?
- What is something that you had to push for in your previous projects?
- What is the most constructive feedback you have received in your career?
- What was one thing you had to persevere for multiple months?
* Why do you want to work for X company?
* Why do you want to leave your current/last company?
* What are you looking for in your next role?
* Tell me about a time when you had a conflict with a co-worker.
* Tell me about a time in which you had a conflict and needed to influence somebody else.
* What project are you currently working on?
* What is the most challenging aspect of your current project?
* What was the most difficult bug that you fixed in the past 6 months?
* How do you tackle challenges? Name a difficult challenge you faced while working on a project, how you overcame it, and what you learned.
* What are you excited about?
* What frustrates you?
* Imagine it is your first day here at the company. What do you want to work on? What features would you improve on?
* What are the most interesting projects you have worked on and how might they be relevant to this company's environment?
* Tell me about a time you had a disagreement with your manager.
* Talk about a project you are most passionate about, or one where you did your best work.
* What does your best day of work look like?
* What is something that you had to push for in your previous projects?
* What is the most constructive feedback you have received in your career?
* What was one thing you had to persevere for multiple months?
## Airbnb
@ -36,130 +35,130 @@ Source: [Glassdoor](https://www.glassdoor.com/Interview/Airbnb-Interview-Questio
While loving to travel or appreciating Airbnb's growth may be good answers, try to demonstrate the deep connection you have with the product.
- What does "belong anywhere" mean to you?
- What large problems in the world would you solve today?
- Why do you like Airbnb?
- 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?
- If you had an unlimited budget and you could go somewhere, where would you go?
- Share one of your trips with us.
- What is the most challenging project in or out of school that you have worked on in the last 6 months.
- What is the thing that you don't want from your last internship/job?
- Give me an example of when you've been a good host.
- One thing you would like to remove from the Airbnb experience.
- What is something new that you can teach your interviewer in a few minutes?
- Tell me about why you want to work here.
- What is the best gift you have ever given or received?
- Tell me about a time you were uncomfortable and how you dealt with it.
- Explain a project that you worked on recently.
- What do you think of Airbnb?
- Tell me something about yourself and why you'd be a good fit for the position.
- Name a situation where you were impressed by a company's customer service.
- How did you work with senior management on large projects as well as multiple internal teams?
- Tell me about a time you had to give someone terrible news.
- If you were a gerbil, which gerbil would you be?
- What excites you about the company?
- How does Airbnb impact our guests and hosts?
- What part of our mission resonates the most with you?
* What does "belong anywhere" mean to you?
* What large problems in the world would you solve today?
* Why do you like Airbnb?
* 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?
* If you had an unlimited budget and you could go somewhere, where would you go?
* Share one of your trips with us.
* What is the most challenging project in or out of school that you have worked on in the last 6 months.
* What is the thing that you don't want from your last internship/job?
* Give me an example of when you've been a good host.
* One thing you would like to remove from the Airbnb experience.
* What is something new that you can teach your interviewer in a few minutes?
* Tell me about why you want to work here.
* What is the best gift you have ever given or received?
* Tell me about a time you were uncomfortable and how you dealt with it.
* Explain a project that you worked on recently.
* What do you think of Airbnb?
* Tell me something about yourself and why you'd be a good fit for the position.
* Name a situation where you were impressed by a company's customer service.
* How did you work with senior management on large projects as well as multiple internal teams?
* Tell me about a time you had to give someone terrible news.
* If you were a gerbil, which gerbil would you be?
* What excites you about the company?
* How does Airbnb impact our guests and hosts?
* What part of our mission resonates the most with you?
## Amazon
Source: [Glassdoor](https://www.glassdoor.com/Interview/Amazon-Interview-Questions-E6036.htm)
- How do you deal with a failed deadline?
- Why do you want to work for Amazon?
- Talked about a situation where you had a conflict with a teammate.
- In my professional experience have you worked on something without getting approval from your manager?
- Tell me a situation where you would have done something differently from what you actually did.
- What is the most exceedingly bad misstep you at any point made?
- Describe what Human Resource means to you.
- How would you improve Amazon's website?
* How do you deal with a failed deadline?
* Why do you want to work for Amazon?
* Talked about a situation where you had a conflict with a teammate.
* In my professional experience have you worked on something without getting approval from your manager?
* Tell me a situation where you would have done something differently from what you actually did.
* What is the most exceedingly bad misstep you at any point made?
* Describe what Human Resource means to you.
* How would you improve Amazon's website?
## Dropbox
Source: [Glassdoor](https://www.glassdoor.com/Interview/Dropbox-Interview-Questions-E415350.htm)
- Talk about your favorite project.
- If you were hired here what would you do?
- State an experience about how you solved a technical problem. Be specific about the diagnosis and process.
* Talk about your favorite project.
* If you were hired here what would you do?
* State an experience about how you solved a technical problem. Be specific about the diagnosis and process.
## Hired
Source: [Glassdoor](https://hired.com/blog/candidates/10-top-interview-questions-how-to-answer/)
- Tell me about yourself.
- What is your biggest strength and area of growth?
- Why are you interested in this opportunity?
- What are your salary expectations?
- Why are you looking to leave your current company?
- What is your biggest strength and area of growth?
- Tell me about a time your work responsibilities got a little overwhelming. What did you do?
- Give me an example of a time when you had a difference of opinion with a team member. How did you handle that?
- Tell me about a challenge you faced recently in your role. How did you tackle it? What was the outcome?
- Where do you want to be in five years?
- Tell me about a time you needed information from someone who wasn't responsive. What did you do?
* Tell me about yourself.
* What is your biggest strength and area of growth?
* Why are you interested in this opportunity?
* What are your salary expectations?
* Why are you looking to leave your current company?
* What is your biggest strength and area of growth?
* Tell me about a time your work responsibilities got a little overwhelming. What did you do?
* Give me an example of a time when you had a difference of opinion with a team member. How did you handle that?
* Tell me about a challenge you faced recently in your role. How did you tackle it? What was the outcome?
* Where do you want to be in five years?
* Tell me about a time you needed information from someone who wasn't responsive. What did you do?
## Lyft
Source: [Glassdoor](https://www.glassdoor.com/Interview/Lyft-Interview-Questions-E700614.htm)
- Tell me about your most interesting/challenging project to date.
- Why Lyft? What are you looking for in the next role?
* Tell me about your most interesting/challenging project to date.
* Why Lyft? What are you looking for in the next role?
## Palantir
Source: [Glassdoor](https://www.glassdoor.com/Interview/Palantir-Technologies-Interview-Questions-E236375.htm)
- How do you deal with difficult coworkers? Think about specific instances where you resolved conflicts.
- How did you win over the difficult employees?
- Tell me about an analytical problem that you have worked on in the past.
- What are your three strengths and three weaknesses?
- If you were in charge of picking projects for Palantir, what problem would you try to solve?
- **What is something 90% of people disagree with you about?**
- What are some of the best and worse things about your current company?
- **What is broken around you?**
- What would your manager say about you?
- Describe Palantir to your grandmother.
- Teach me something you've learned?
- Tell me a time when you predicted something?
- If your supervisors were to rate you on a scale of 1-10 what would they rate you?
- What was the most fun thing you did recently?
- Tell me the story of how you became who you are today and what made you apply to Palantir.
* How do you deal with difficult coworkers? Think about specific instances where you resolved conflicts.
* How did you win over the difficult employees?
* Tell me about an analytical problem that you have worked on in the past.
* What are your three strengths and three weaknesses?
* If you were in charge of picking projects for Palantir, what problem would you try to solve?
* **What is something 90% of people disagree with you about?**
* What are some of the best and worse things about your current company?
* **What is broken around you?**
* What would your manager say about you?
* Describe Palantir to your grandmother.
* Teach me something you've learned?
* Tell me a time when you predicted something?
* If your supervisors were to rate you on a scale of 1-10 what would they rate you?
* What was the most fun thing you did recently?
* Tell me the story of how you became who you are today and what made you apply to Palantir.
## Slack
Source: [Glassdoor](https://www.glassdoor.com/Interview/Slack-Interview-Questions-E950758.htm)
- Tell me something about your internship.
- Why do you want to join Slack?
- Tell me about your past projects.
- Explain me your toughest project and the working architecture.
- Apart from technical knowledge what did you learn during your internship?
- If someone has a different viewpoint to do a project like different programming language, how would handle this situation?
- What are your most interesting subjects and why?
- Did you find any bug in Slack?
- What is your favorite feature and why?
* Tell me something about your internship.
* Why do you want to join Slack?
* Tell me about your past projects.
* Explain me your toughest project and the working architecture.
* Apart from technical knowledge what did you learn during your internship?
* If someone has a different viewpoint to do a project like different programming language, how would handle this situation?
* What are your most interesting subjects and why?
* Did you find any bug in Slack?
* What is your favorite feature and why?
## Stack Overflow
Source: [Glassdoor](https://hired.com/blog/candidates/10-top-interview-questions-how-to-answer/)
- What have you built?
- What is the hardest technical problem you have run into?
- How did you solve it?
- Where do you see yourself in 5 years?
- Why do you want to work here?
- How do you handle disagreements with coworkers?
* What have you built?
* What is the hardest technical problem you have run into?
* How did you solve it?
* Where do you see yourself in 5 years?
* Why do you want to work here?
* How do you handle disagreements with coworkers?
## Stripe
Source: [Glassdoor](https://www.glassdoor.com/Interview/Stripe-Interview-Questions-E671932.htm)
- How do you stay up to date with the latest technologies?
- Explain a project that you worked on recently that was difficult.
- Where do you see yourself in five years?
* How do you stay up to date with the latest technologies?
* Explain a project that you worked on recently that was difficult.
* Where do you see yourself in five years?
## Twitter
Source: [Glassdoor](https://www.glassdoor.com/Interview/Twitter-Interview-Questions-E100569.htm)
- What would your previous boss say your biggest strength was?
* What would your previous boss say your biggest strength was?

@ -1,8 +1,7 @@
Cover Letter
==
# Cover Letter
- A short introduction describing who you are and what you're looking for.
- What projects have you enjoyed working on?
- Which have you disliked? What motivates you?
- Links to online profiles you use (GitHub, Twitter, etc).
- A description of your work history (whether as a resume, LinkedIn profile, or prose).
* A short introduction describing who you are and what you're looking for.
* What projects have you enjoyed working on?
* Which have you disliked? What motivates you?
* Links to online profiles you use (GitHub, Twitter, etc).
* A description of your work history (whether as a resume, LinkedIn profile, or prose).

@ -1,5 +1,4 @@
Interview Formats
==
# Interview Formats
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.
@ -7,127 +6,127 @@ For on-site interviews at smaller (non-public) companies, most will allow (and p
## Companies
- [Airbnb](#airbnb)
- [Asana](#asana)
- [Dropbox](#dropbox)
- [Facebook](#facebook)
- [Google](#google)
- [Lyft](#lyft)
- [Palantir](#palantir)
- [WhatsApp](#whatsapp)
* [Airbnb](#airbnb)
* [Asana](#asana)
* [Dropbox](#dropbox)
* [Facebook](#facebook)
* [Google](#google)
* [Lyft](#lyft)
* [Palantir](#palantir)
* [WhatsApp](#whatsapp)
### Airbnb
- Recruiter phone screen.
- Technical phone interview:
- 1 or 2 x Algorithm/front end on CoderPad/CodePen.
- On-site (General):
- 2 x Algorithm coding on CoderPad.
- 1 x System design/architecture.
- 1 x Past experience/project.
- 2 x Cross functional.
- On-site (Front End):
- 2 x Front end coding on CodePen. Use any framework/library.
- 1 x General coding on your own laptop.
- 1 x Past experience/project.
- 2 x Cross functional.
- Tips:
- All sessions involve coding on your own laptop. Prepare your development environment in advance.
- You are allowed to look up APIs if you need to.
- They seem to place high emphasis on compilable, runnable code in all their coding rounds.
- 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.
* Recruiter phone screen.
* Technical phone interview:
* 1 or 2 x Algorithm/front end on CoderPad/CodePen.
* On-site (General):
* 2 x Algorithm coding on CoderPad.
* 1 x System design/architecture.
* 1 x Past experience/project.
* 2 x Cross functional.
* On-site (Front End):
* 2 x Front end coding on CodePen. Use any framework/library.
* 1 x General coding on your own laptop.
* 1 x Past experience/project.
* 2 x Cross functional.
* Tips:
* All sessions involve coding on your own laptop. Prepare your development environment in advance.
* You are allowed to look up APIs if you need to.
* They seem to place high emphasis on compilable, runnable code in all their coding rounds.
* 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.
### Asana
- Recruiter phone screen.
- Technical phone interview.
- On-site (Product Engineer):
- 3 x Algorithm and system design on whiteboard within the same session.
- 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.
- Tips:
- No front end questions were asked.
- 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.
- All 4 sessions involve algorithms and system design. One of the sessions will be conducted by an Engineering Manager.
- The last session will involve coding on your own laptop. Prepare your development environment in advance.
- Regardless of Product Engineer or Engineering Generalist position, their interview format and questions are similar.
* Recruiter phone screen.
* Technical phone interview.
* On-site (Product Engineer):
* 3 x Algorithm and system design on whiteboard within the same session.
* 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.
* Tips:
* No front end questions were asked.
* 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.
* All 4 sessions involve algorithms and system design. One of the sessions will be conducted by an Engineering Manager.
* The last session will involve coding on your own laptop. Prepare your development environment in advance.
* Regardless of Product Engineer or Engineering Generalist position, their interview format and questions are similar.
### Dropbox
- Recruiter phone screen.
- Technical phone interviews:
- 2 x Algorithm/front end on CoderPad/CodePen.
- On-site (Front End):
- 2 x Front end on CodePen. Only Vanilla JS or jQuery allowed.
- 1 x General coding on CoderPad.
- 1 x All around. Meet with an Engineering Manager and discussing past experiences and working style.
- Tips:
- You can code on your own laptop and look up APIs.
- Dropbox recruiters are very nice and will give you helpful information on what kind of questions to expect for the upcoming sessions.
- 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.
* Recruiter phone screen.
* Technical phone interviews:
* 2 x Algorithm/front end on CoderPad/CodePen.
* On-site (Front End):
* 2 x Front end on CodePen. Only Vanilla JS or jQuery allowed.
* 1 x General coding on CoderPad.
* 1 x All around. Meet with an Engineering Manager and discussing past experiences and working style.
* Tips:
* You can code on your own laptop and look up APIs.
* Dropbox recruiters are very nice and will give you helpful information on what kind of questions to expect for the upcoming sessions.
* 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.
### Facebook
- Recruiter phone screen.
- Technical phone interviews:
- 1 or 2 x Algorithm/front end on Skype/CoderPad.
- On-site (Front End):
- 2 x Technical coding interview on whiteboard (Ninja).
- 1 x Behavioural (Jedi). Meet with an Engineering Manager and discussing past experiences and working style.
- 1 x Design/architecture on whiteboard (Pirate).
- Tips:
- You are only allowed to use the whiteboard (or wall). No laptops involved.
- 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.
- For the Ninja rounds, you may be asked one to two questions depending on how fast you progress through the question.
* Recruiter phone screen.
* Technical phone interviews:
* 1 or 2 x Algorithm/front end on Skype/CoderPad.
* On-site (Front End):
* 2 x Technical coding interview on whiteboard (Ninja).
* 1 x Behavioural (Jedi). Meet with an Engineering Manager and discussing past experiences and working style.
* 1 x Design/architecture on whiteboard (Pirate).
* Tips:
* You are only allowed to use the whiteboard (or wall). No laptops involved.
* 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.
* For the Ninja rounds, you may be asked one to two questions depending on how fast you progress through the question.
### Google
- Recruiter phone screen.
- Technical phone interview:
- 1 or 2 x algorithm on Google Doc.
- On-site (Front End):
- 3 x Front end on whiteboard. Have to use Vanilla JS (or at the most, jQuery).
- 2 x Algorithm on whiteboard.
- Team matching.
- Speak with managers from different teams who are interested in your profile.
- Tips:
- You are only allowed to use the whiteboard. No laptops involved.
- In rare cases, candidates may even be allowed to skip the phone interview round and advanced to on-site directly.
- For non-fresh grads, you only receive an offer if you are successfully matched with a team.
* Recruiter phone screen.
* Technical phone interview:
* 1 or 2 x algorithm on Google Doc.
* On-site (Front End):
* 3 x Front end on whiteboard. Have to use Vanilla JS (or at the most, jQuery).
* 2 x Algorithm on whiteboard.
* Team matching.
* Speak with managers from different teams who are interested in your profile.
* Tips:
* You are only allowed to use the whiteboard. No laptops involved.
* In rare cases, candidates may even be allowed to skip the phone interview round and advanced to on-site directly.
* For non-fresh grads, you only receive an offer if you are successfully matched with a team.
### Lyft
- Recruiter phone screen.
- Technical phone interview:
- 1 x Algorithm/Front end over JSFiddle.
- On-site (Front End):
- 4 x Front end on Coderpad/your own laptop. Use any language/framework.
- 1 x Behavioural. Meet with an Engineering Manager and go through candidate's resume.
- Tips:
- Can use whiteboard and/or laptop.
- For front end coding, I opted to use React and had to set up the projects on the spot using `create-react-app`.
* Recruiter phone screen.
* Technical phone interview:
* 1 x Algorithm/Front end over JSFiddle.
* On-site (Front End):
* 4 x Front end on Coderpad/your own laptop. Use any language/framework.
* 1 x Behavioural. Meet with an Engineering Manager and go through candidate's resume.
* Tips:
* Can use whiteboard and/or laptop.
* For front end coding, I opted to use React and had to set up the projects on the spot using `create-react-app`.
### Palantir
- Recruiter phone screen.
- Technical phone interview:
- 1 x Algorithm over HackerRank CodePair and Skype.
- On-site (General):
- 2 x Algorithm on whiteboard.
- 1 x Decomposition (system design) on whiteboard.
- On-site (Front End):
- 1 x Front end on your own laptop. This session lasts about 1.5 hours. Use any library/framework.
- 1 x Decomposition (system design) on whiteboard.
- Tips:
- I opted to use React and had to set up projects on the spot using `create-react-app`.
- You may be asked to meet with Engineering Managers after the technical sessions and it's not necessarily a good/bad thing.
* Recruiter phone screen.
* Technical phone interview:
* 1 x Algorithm over HackerRank CodePair and Skype.
* On-site (General):
* 2 x Algorithm on whiteboard.
* 1 x Decomposition (system design) on whiteboard.
* On-site (Front End):
* 1 x Front end on your own laptop. This session lasts about 1.5 hours. Use any library/framework.
* 1 x Decomposition (system design) on whiteboard.
* Tips:
* I opted to use React and had to set up projects on the spot using `create-react-app`.
* You may be asked to meet with Engineering Managers after the technical sessions and it's not necessarily a good/bad thing.
### WhatsApp
- Recruiter phone screen.
- Technical phone interview:
- 2 x Algorithm over CoderPad.
- On-site (Web Client Developer):
- 4 x Algorithm on whiteboard.
- Tips:
- No front end questions were asked.
- 1 of the interviewers is an Engineering Manager.
* Recruiter phone screen.
* Technical phone interview:
* 2 x Algorithm over CoderPad.
* On-site (Web Client Developer):
* 4 x Algorithm on whiteboard.
* Tips:
* No front end questions were asked.
* 1 of the interviewers is an Engineering Manager.

@ -1,5 +1,4 @@
Negotiation
==
# Negotiation
### Ten Rules of Negotiation

@ -1,27 +1,26 @@
Psychological Tricks
==
# Psychological Tricks
Here are some psychological tricks that will help you ace a job interview.
- Tailor your answers to the interviewer's age.
- Generation Y interviewers (between 20 and 30): Bring along visual samples of your work and highlight your ability to multitask.
- Generation X interviewers (between 30 and 50): Emphasize your creativity and mention how work/life balance contributes to your success.
- Baby Boomer interviewers (between 50 and 70): Show that you work hard and demonstrate respect for what they've achieved.
- Hold your palms open or steeple your hands.
- Find something in common with your interviewer.
- Mirror the interviewer's body language.
- Compliment the interviewer and the organization without self-promoting.
- 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.
- Show confidence and deference simultaneously.
- 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]."
- Emphasize how you took control of events in your previous jobs.
- To impress your interviewer, you should talk about past work experiences where you took initiative.
- Be candid about your weaknesses.
- 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.
- Speak expressively.
- Showcase your potential.
- 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.
* Tailor your answers to the interviewer's age.
* Generation Y interviewers (between 20 and 30): Bring along visual samples of your work and highlight your ability to multitask.
* Generation X interviewers (between 30 and 50): Emphasize your creativity and mention how work/life balance contributes to your success.
* Baby Boomer interviewers (between 50 and 70): Show that you work hard and demonstrate respect for what they've achieved.
* Hold your palms open or steeple your hands.
* Find something in common with your interviewer.
* Mirror the interviewer's body language.
* Compliment the interviewer and the organization without self-promoting.
* 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.
* Show confidence and deference simultaneously.
* 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]."
* Emphasize how you took control of events in your previous jobs.
* To impress your interviewer, you should talk about past work experiences where you took initiative.
* Be candid about your weaknesses.
* 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.
* Speak expressively.
* Showcase your potential.
* 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.
###### References
- [Business Insider](http://www.businessinsider.com/psychological-tricks-to-ace-job-interview-2015-11)
* [Business Insider](http://www.businessinsider.com/psychological-tricks-to-ace-job-interview-2015-11)

@ -1,110 +1,109 @@
Questions to Ask
==
# Questions to Ask
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.
### General
- **What are you most proud about in your career so far?**
- **What is the most important/valuable thing you have learnt from working here?**
- How do your clients and customers define success?
- What would you change around here if you could?
- What are some weaknesses of the organization?
- What does a typical day look like for you?
- What do you think the company can improve at?
- How would you see yourself growing at this company in the next few years?
- Was there a time where you messed up and how was it handled?
- Why did you choose to come to this company?
- When you were last interviewing, what were some of your other options, and what made you choose this company?
- What was something you wish someone would have told you before you joined?
- What was your best moment so far at the company?
* **What are you most proud about in your career so far?**
* **What is the most important/valuable thing you have learnt from working here?**
* How do your clients and customers define success?
* What would you change around here if you could?
* What are some weaknesses of the organization?
* What does a typical day look like for you?
* What do you think the company can improve at?
* How would you see yourself growing at this company in the next few years?
* Was there a time where you messed up and how was it handled?
* Why did you choose to come to this company?
* When you were last interviewing, what were some of your other options, and what made you choose this company?
* What was something you wish someone would have told you before you joined?
* What was your best moment so far at the company?
### Culture
- **What is the most frustrating part about working here?**
- **What is unique about working at this company that you have not experienced elsewhere?**
- **What is something you wish were different about your job?**
- How will the work I will be doing contribute to the organization's mission?
- What do you like about working here?
- What is your policy on working from home/remotely?
- (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?
- Does the company culture encourage entrepreneurship? Could you give me any specific examples?
* **What is the most frustrating part about working here?**
* **What is unique about working at this company that you have not experienced elsewhere?**
* **What is something you wish were different about your job?**
* How will the work I will be doing contribute to the organization's mission?
* What do you like about working here?
* What is your policy on working from home/remotely?
* (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?
* Does the company culture encourage entrepreneurship? Could you give me any specific examples?
### Technical
These questions are suitable for any technical role.
- **What are the engineering challenges that the company/team is facing?**
- **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?**
- **What is the most costly technical decision made early on that the company is living with now?**
- **What is the most fulfilling/exciting/technically complex project that you've worked on here so far?**
- How do you evaluate new technologies? Who makes the final decisions?
- How do you know what to work on each day?
- How would you describe your engineering culture?
- How has your role changed since joining the company?
- What is your stack? What is the rationale for/story behind this specific stack?
- Do you tend to roll your own solutions more often or rely on third party tools? What's the rationale in a specific case?
- How does the engineering team balance resources between feature requests and engineering maintenance?
- What do you measure? What are your most important product metrics?
- What does the company do to nurture and train its employees?
- 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?
- 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?
- 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?
* **What are the engineering challenges that the company/team is facing?**
* **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?**
* **What is the most costly technical decision made early on that the company is living with now?**
* **What is the most fulfilling/exciting/technically complex project that you've worked on here so far?**
* How do you evaluate new technologies? Who makes the final decisions?
* How do you know what to work on each day?
* How would you describe your engineering culture?
* How has your role changed since joining the company?
* What is your stack? What is the rationale for/story behind this specific stack?
* Do you tend to roll your own solutions more often or rely on third party tools? What's the rationale in a specific case?
* How does the engineering team balance resources between feature requests and engineering maintenance?
* What do you measure? What are your most important product metrics?
* What does the company do to nurture and train its employees?
* 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?
* 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?
* 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?
### Product
- Tell me about the main products of your company.
- What is the current version of product? (If it is v1.0 or similar - there could be a lot of chaos to work with)
- What products are your main competitors?
- What makes your product competitive?
- 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)
* Tell me about the main products of your company.
* What is the current version of product? (If it is v1.0 or similar - there could be a lot of chaos to work with)
* What products are your main competitors?
* What makes your product competitive?
* 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)
### Management
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.
- **How do you train/ramp up engineers who are new to the team?**
- **What does success look like for your team?**
- **What qualities do you look out for when hiring for this role?**
- **What are the strengths and weaknesses of the current team? What is being done to improve upon the weaknesses?**
- **Can you tell me about a time you resolved an interpersonal conflict?**
- How did you become a manager?
- How do your engineers know what to work on each day?
- What is your team's biggest challenge right now?
- How do you measure individual performance?
- How often are 1:1s conducted?
- What is the current team composition like?
- What opportunities are available to switch roles? How does this work?
* **How do you train/ramp up engineers who are new to the team?**
* **What does success look like for your team?**
* **What qualities do you look out for when hiring for this role?**
* **What are the strengths and weaknesses of the current team? What is being done to improve upon the weaknesses?**
* **Can you tell me about a time you resolved an interpersonal conflict?**
* How did you become a manager?
* How do your engineers know what to work on each day?
* What is your team's biggest challenge right now?
* How do you measure individual performance?
* How often are 1:1s conducted?
* What is the current team composition like?
* What opportunities are available to switch roles? How does this work?
### Leadership
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.
- How are you funded?
- Are you profitable? If no, what's your plan for becoming profitable?
- What assurance do you have that this company will be successful?
- Tell me about your reporting structure.
- How does the company decide on what to work on next?
* How are you funded?
* Are you profitable? If no, what's your plan for becoming profitable?
* What assurance do you have that this company will be successful?
* Tell me about your reporting structure.
* How does the company decide on what to work on next?
### HR
- **How do you see this position evolving in the next three years?**
- **Who is your ideal candidate and how can I make myself more like them?**
- What concerns/reservations do you have about me for this position?
- What can I help to clarify that would make hiring me an easy decision?
- How does the management team deal with mistakes?
- If you could hire anyone to join your team, who would that be and why?
- How long does the average engineer stay at the company?
- Why have the last few people left?
- Have you ever thought about leaving? If you were to leave, where would you go?
* **How do you see this position evolving in the next three years?**
* **Who is your ideal candidate and how can I make myself more like them?**
* What concerns/reservations do you have about me for this position?
* What can I help to clarify that would make hiring me an easy decision?
* How does the management team deal with mistakes?
* If you could hire anyone to join your team, who would that be and why?
* How long does the average engineer stay at the company?
* Why have the last few people left?
* Have you ever thought about leaving? If you were to leave, where would you go?
###### References
- [Business Insider](http://www.businessinsider.sg/impressive-job-interview-questions-2015-3/)
- [Lifehacker](http://lifehacker.com/ask-this-question-to-end-your-job-interview-on-a-good-n-1787624433)
- [Fastcompany](https://www.fastcompany.com/40406730/7-questions-recruiters-at-amazon-spotify-and-more-want-you-to-ask)
- [Questions I'm asking in interviews](http://jvns.ca/blog/2013/12/30/questions-im-asking-in-interviews/)
- [How to interview your interviewers](http://blog.alinelerner.com/how-to-interview-your-interviewers/)
- [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/)
- [A developer's guide to interviewing](https://medium.freecodecamp.org/how-to-interview-as-a-developer-candidate-b666734f12dd)
- [Questions I'm asking in interviews 2017](https://cternus.net/blog/2017/10/10/questions-i-m-asking-in-interviews-2017/)
* [Business Insider](http://www.businessinsider.sg/impressive-job-interview-questions-2015-3/)
* [Lifehacker](http://lifehacker.com/ask-this-question-to-end-your-job-interview-on-a-good-n-1787624433)
* [Fastcompany](https://www.fastcompany.com/40406730/7-questions-recruiters-at-amazon-spotify-and-more-want-you-to-ask)
* [Questions I'm asking in interviews](http://jvns.ca/blog/2013/12/30/questions-im-asking-in-interviews/)
* [How to interview your interviewers](http://blog.alinelerner.com/how-to-interview-your-interviewers/)
* [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/)
* [A developer's guide to interviewing](https://medium.freecodecamp.org/how-to-interview-as-a-developer-candidate-b666734f12dd)
* [Questions I'm asking in interviews 2017](https://cternus.net/blog/2017/10/10/questions-i-m-asking-in-interviews-2017/)

@ -1,12 +1,11 @@
Resume
==
# Resume
The following content is by Christina Ng and rephrased for the purpose of this handbook. You can follow her on [Medium](https://medium.com/@christinang89) or [Quora](https://www.quora.com/profile/Christina-Ng).
## Table of Contents
1. [How Your Resume is Screened](#how-your-resume-is-screened)
1. [10 Ways To Improve Your Resume](#10-ways-to-improve-your-resume)
1. [How Your Resume is Screened](#how-your-resume-is-screened)
1. [10 Ways To Improve Your Resume](#10-ways-to-improve-your-resume)
## How Your Resume is Screened
@ -18,9 +17,9 @@ Before writing your resume, it is important to understand the recruiting structu
Before opening up a position/starting the search for candidates, I usually consult very closely with the team manager/decision maker to find out the specific skill sets that are relevant for the position. These skill sets are typically grouped into "Must have", "Good to have", and "Special bonus".
- "Must have" — Typically, most of the must-haves include a degree (or not) in a relevant technical field, some years (or not) of experience in a particular programming language or technology.
- "Good to have" — Includes experience/familiarity with secondary languages/technologies which may not be directly relevant to what the candidate would be working on, but could be required due to some interfacing with other components of the project. It could also include softer skills such as being a good team player, clear communication, etc.
- "Special bonus" — Recognized skill sets/experiences which are difficult to come by. Probably not a requirement, but would definitely be useful for the position.
* "Must have" — Typically, most of the must-haves include a degree (or not) in a relevant technical field, some years (or not) of experience in a particular programming language or technology.
* "Good to have" — Includes experience/familiarity with secondary languages/technologies which may not be directly relevant to what the candidate would be working on, but could be required due to some interfacing with other components of the project. It could also include softer skills such as being a good team player, clear communication, etc.
* "Special bonus" — Recognized skill sets/experiences which are difficult to come by. Probably not a requirement, but would definitely be useful for the position.
Now that I am armed with this list, the search for candidates begin.
@ -32,7 +31,7 @@ When I am looking at your resume, I am doing a keyword match against the skill s
There are lots of articles writing about how recruiters only spend an average of about 10 seconds to screen each resume. The news is, this is true because resume screening is such a menial, robotic and repetitive task. In fact, many applicant tracking systems (ATS) now are so advanced that they can parse your resume automatically, search for specific keywords in your resume, and score your resume based on the weights pre-assigned to each keyword.
Finding a job is a two-way fit — the company wants someone with the relevant skills required, but it is also important for the applicant to fit in the company culture, and be able to gain something out of his stint. Hence, honesty is the single most important criteria in a resume.
Finding a job is a two-way fitthe company wants someone with the relevant skills required, but it is also important for the applicant to fit in the company culture, and be able to gain something out of his stint. Hence, honesty is the single most important criteria in a resume.
There is a delicate balance between finding the right job vs. finding a job. Getting rejected does not always mean you are not good enough. Sometimes, it just means you are not a right fit for what the company is looking for.
@ -48,8 +47,8 @@ I've often received resumes with no cover letters, and I am perfectly fine with
Some small nitpicks:
- Make sure that the cover letter is addressed to the right person (either the name of the recruiter if it is known, or to a generic hiring manager) and company.
- Run a spell check.
* Make sure that the cover letter is addressed to the right person (either the name of the recruiter if it is known, or to a generic hiring manager) and company.
* Run a spell check.
#### 2. Length of resume
@ -57,28 +56,28 @@ Your resume should be kept to 1 page or a MAXIMUM of 2 pages. Include only your
Information that a recruiter wants to know:
- Name, email, contact number.
- Education details: College, Major, GPA, Sample classes (optional, but if you list, make sure its classes that you scored well in and are relevant to your area of interest), academic awards, availability.
- If you have studied abroad, you can list that too.
- Projects that you have worked on.
- Work experience/co-curricular activities.
- Skills/other interests.
- Street cred - GitHub/StackOverflow/LinkedIn profile (optional, but highly recommended).
* Name, email, contact number.
* Education details: College, Major, GPA, Sample classes (optional, but if you list, make sure its classes that you scored well in and are relevant to your area of interest), academic awards, availability.
* If you have studied abroad, you can list that too.
* Projects that you have worked on.
* Work experience/co-curricular activities.
* Skills/other interests.
* Street cred - GitHub/StackOverflow/LinkedIn profile (optional, but highly recommended).
Information nobody needs to know:
- Your profile picture.
- Address, home phone number, gender, religion, race, marital status, etc etc.
- Elementary, middle, high school.
- Your low GPA.
- Anything less recent than 3-4 years unless they are valid job experiences.
- Anything about your parents/siblings, their names, occupation, etc.
- Your life story.
- Anything not relevant to the job you are applying for (e.g. that you have a driving license when you are applying to be a programmer).
* Your profile picture.
* Address, home phone number, gender, religion, race, marital status, etc etc.
* Elementary, middle, high school.
* Your low GPA.
* Anything less recent than 3-4 years unless they are valid job experiences.
* Anything about your parents/siblings, their names, occupation, etc.
* Your life story.
* Anything not relevant to the job you are applying for (e.g. that you have a driving license when you are applying to be a programmer).
Ideally, keep it short, concise, but as detailed as possible.
#### 3. GPA does matter
#### 3. GPA does matter
Everyone wants the cream of the crop. In the absence of a standardized test, GPA serves as that indicator. **While GPA may not necessarily be a good indication of how well you can code, a high GPA would definitely put you in a more favorable position to the recruiter.**
@ -92,10 +91,10 @@ Also, when you list your GPA/results, try to benchmark it. Instead of simply lis
Are you looking for a summer internship/full-time employment? What position are you applying for? Read the job description and know the job you are applying for!!
**"Work experience" does not mean any work experience; it means *relevant* work experience.** If you are applying for a developer position, the recruiter is not interested to know that you were a student escort for girls walking back to their apartments at night, nor that you were a cashier at Starbucks. You would be better off writing about the project you did for some programming class - yes, even if it was just a school project. Tailor your experiences and projects according to the job you are applying for. Pick relevant details to emphasize on and do not be hesitant to drop stuff completely if they are totally irrelevant. Quality over quantity.
**"Work experience" does not mean any work experience; it means _relevant_ work experience.** If you are applying for a developer position, the recruiter is not interested to know that you were a student escort for girls walking back to their apartments at night, nor that you were a cashier at Starbucks. You would be better off writing about the project you did for some programming class - yes, even if it was just a school project. Tailor your experiences and projects according to the job you are applying for. Pick relevant details to emphasize on and do not be hesitant to drop stuff completely if they are totally irrelevant. Quality over quantity.
- Make sure the description is comprehensive. Avoid writing "Software engineering intern - write code". You are better off not writing anything.
- Based on my experience, most fresh grads do not have extremely relevant job experience (unless you are lucky to have scored a really rewarding internship). For developer positions, I think it is ok to not have any job experience and just list projects.
* Make sure the description is comprehensive. Avoid writing "Software engineering intern - write code". You are better off not writing anything.
* Based on my experience, most fresh grads do not have extremely relevant job experience (unless you are lucky to have scored a really rewarding internship). For developer positions, I think it is ok to not have any job experience and just list projects.
#### 5. Reverse chronological order
@ -103,24 +102,24 @@ Always list your resume in reverse chronological order - the most recent at the
#### 6. Make sure you are contactable
- Get a proper email account with ideally your first name and last name, eg. "john.doe@gmail.com" instead of "angrybirds88@gmail.com".
- If you are using your school's .edu email, try to have an alias like "john.doe@xxx.edu" instead of "a002342342@xxx.edu".
- Avoid emails like "me@christi.na" or "admin@[mycooldomain].com" -- because it is very prone to typo errors.
- Make sure the number you have listed is the best way to reach you. The last thing you want is to miss the call from the recruiter because you typed the wrong number, or you are not available on that number during office hours (most probably the times the recruiter will call).
* Get a proper email account with ideally your first name and last name, eg. "john.doe@gmail.com" instead of "angrybirds88@gmail.com".
* If you are using your school's .edu email, try to have an alias like "john.doe@xxx.edu" instead of "a002342342@xxx.edu".
* Avoid emails like "me@christi.na" or "admin@[mycooldomain].com" -- because it is very prone to typo errors.
* Make sure the number you have listed is the best way to reach you. The last thing you want is to miss the call from the recruiter because you typed the wrong number, or you are not available on that number during office hours (most probably the times the recruiter will call).
#### 7. Layout/Formatting/Design
- Be consistent about the way you format your resume. Italics, underline, bold, and how they are used.
- Keep to a single standard font (avoid fancy fonts like Comic Sans or whatever) and do not have too many varying styles/font sizes/color
- Be consistent about the way you list your dates (eg. May 2011 - Aug 2011). Avoid using numerals for both month and date due to the difference in style for MMDD and DDMM in different countries. Dates like "Aug 2011 - June 12" just show that you have zero attention to detail.
- Unless you are applying for a design job, just stick to the standard "table" style for the resume. There is nothing wrong with the standard style, and it helps the recruiter screen your resume more efficiently since they are trained through experience to read that format. It would also help in the automatic scoring by the ATS. The last thing you want is for your application to be rejected because the system could not parse your resume for it to be scored. That said, I am not discouraging you from coming up with your own design. It is nice to read something different. Just be aware of the risks you could be taking.
- Name your file `firstname_lastname_resume.pdf` instead of `resume.pdf` - it is easier for recruiters to search/forward.
- PDF preferred over Word doc.
- Be consistent about bullet points.
- Your resume should not look sparse. (Come on, it is only 1 page!) If you really have trouble filling it up, you are either not thinking hard enough, or not doing enough. In the case of the latter, consider working on your personal projects (i.e. stuff you can post on GitHub). That said, do not write stuff just to fill space. Read point 4.
- This should be common sense, but do not commit fraud, i.e. apply for the same job using a different name, or using your friend's resume to apply for the same job. Some ATS issues an indicator if they suspect the application to be a duplicate.
- It's important to note the layout of your resume. If you choose to quickly upload your resume via an auto-fill program, understand that the program will read your resume from top to bottom, left to right. This is good to keep in mind when developing the layout of your resume.
- Try to keep white space down to a minimum. This will also help reduce the length of your resume to one page. Reduce margins and paddings reasonably.
* Be consistent about the way you format your resume. Italics, underline, bold, and how they are used.
* Keep to a single standard font (avoid fancy fonts like Comic Sans or whatever) and do not have too many varying styles/font sizes/color
* Be consistent about the way you list your dates (eg. May 2011 - Aug 2011). Avoid using numerals for both month and date due to the difference in style for MMDD and DDMM in different countries. Dates like "Aug 2011 - June 12" just show that you have zero attention to detail.
* Unless you are applying for a design job, just stick to the standard "table" style for the resume. There is nothing wrong with the standard style, and it helps the recruiter screen your resume more efficiently since they are trained through experience to read that format. It would also help in the automatic scoring by the ATS. The last thing you want is for your application to be rejected because the system could not parse your resume for it to be scored. That said, I am not discouraging you from coming up with your own design. It is nice to read something different. Just be aware of the risks you could be taking.
* Name your file `firstname_lastname_resume.pdf` instead of `resume.pdf` - it is easier for recruiters to search/forward.
* PDF preferred over Word doc.
* Be consistent about bullet points.
* Your resume should not look sparse. (Come on, it is only 1 page!) If you really have trouble filling it up, you are either not thinking hard enough, or not doing enough. In the case of the latter, consider working on your personal projects (i.e. stuff you can post on GitHub). That said, do not write stuff just to fill space. Read point 4.
* This should be common sense, but do not commit fraud, i.e. apply for the same job using a different name, or using your friend's resume to apply for the same job. Some ATS issues an indicator if they suspect the application to be a duplicate.
* It's important to note the layout of your resume. If you choose to quickly upload your resume via an auto-fill program, understand that the program will read your resume from top to bottom, left to right. This is good to keep in mind when developing the layout of your resume.
* Try to keep white space down to a minimum. This will also help reduce the length of your resume to one page. Reduce margins and paddings reasonably.
#### 8. Listing Your skills
@ -130,10 +129,9 @@ Ideally, if your resume is good enough, the recruiter should already know what y
#### 9. Projects
- Ideally, 1-2 lines about the project, 2-3 lines about your role, what technologies you used, what you did, your learning, etc etc. These can be Final Year Projects, Research projects, projects for a particular class, freelance projects, or just personal projects (ie. GitHub stuff).
- Ideally, 2 to 3 projects that align with your interests/position you are applying for.
- Avoid using titles such as "Project for [module code]". Sorry, the recruiter has no idea what class is represented by the module code.
Ideally, you want the project section to demonstrate your personality and skills, and be the talking point during the interview.
* Ideally, 1-2 lines about the project, 2-3 lines about your role, what technologies you used, what you did, your learning, etc etc. These can be Final Year Projects, Research projects, projects for a particular class, freelance projects, or just personal projects (ie. GitHub stuff).
* Ideally, 2 to 3 projects that align with your interests/position you are applying for.
* Avoid using titles such as "Project for [module code]". Sorry, the recruiter has no idea what class is represented by the module code. Ideally, you want the project section to demonstrate your personality and skills, and be the talking point during the interview.
#### 10. Online profile/other interests
@ -143,5 +141,5 @@ If you have some space on your resume, it is good to list additional interests o
###### References
- [Screening your resume is like playing word search](https://medium.com/@christinang89/screening-your-resume-is-like-playing-word-search-60f4d0e60840)
- [10 tips to get past resume screening for College Students/Grads](https://christinang89.quora.com/10-tips-to-get-past-resume-screening-for-College-Students-Grads)
* [Screening your resume is like playing word search](https://medium.com/@christinang89/screening-your-resume-is-like-playing-word-search-60f4d0e60840)
* [10 tips to get past resume screening for College Students/Grads](https://christinang89.quora.com/10-tips-to-get-past-resume-screening-for-College-Students-Grads)

@ -1,27 +1,26 @@
Self Introduction
==
# Self Introduction
You can rephrase the question like this:
"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?"
"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?"
### The Elevator Pitch
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:
- Sell yourself
- The whole point of this is to get you a job or make a connection that benefits your career.
- Tell them who you are, who you work for (or school and major), and what you do.
- KISS (Keep It Simple, Stupid)
- Tell them some highlights from your favorite / most impressive projects.
- 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.
- Why do *they* want *you*?
- 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.
- PRACTICE!
- 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.
* Sell yourself
* The whole point of this is to get you a job or make a connection that benefits your career.
* Tell them who you are, who you work for (or school and major), and what you do.
* KISS (Keep It Simple, Stupid)
* Tell them some highlights from your favorite / most impressive projects.
* 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.
* Why do _they_ want _you_?
* 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.
* PRACTICE!
* 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.
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.
###### References
- [8 Secrets to Software Engineer Self Introduction](http://blog.gainlo.co/index.php/2016/10/14/8-secretes-software-engineer-self-introduction)
* [8 Secrets to Software Engineer Self Introduction](http://blog.gainlo.co/index.php/2016/10/14/8-secretes-software-engineer-self-introduction)

@ -1,5 +1,4 @@
Preparing for a Coding Interview
==
# Preparing for a Coding Interview
### Picking a Programming Language
@ -13,9 +12,9 @@ Java is a decent choice too but having to constantly declare types in your code
One exception to the convention of allowing you to "pick any programming language you want" is when you are interviewing for a domain-specific position, such as Front End/iOS/Android Engineer roles, in which you would need to be familiar with coding algorithms in JavaScript, Objective-C/Swift and Java respectively. If you need to use a data structure that the language does not support, such as a Queue or Heap in JavaScript, perhaps try asking the interviewer whether you can assume that you have a data structure that implements certain methods with specified time complexities. If the implementation of that data structure is not crucial to solving the problem, the interviewer will usually allow it. In reality, being aware of existing data structures and selecting the appropriate ones to tackle the problem at hand is more important than knowing the intricate implementation details.
### Review your CS101
### Review your CS101
If you have been out of college for a while, it is highly advisable to review CS fundamentals — Algorithms and Data Structures. Personally, I prefer to review as I practice, so I scan through my college notes and review the various algorithms as I work on algorithm problems from LeetCode and Cracking the Coding Interview.
If you have been out of college for a while, it is highly advisable to review CS fundamentalsAlgorithms and Data Structures. Personally, I prefer to review as I practice, so I scan through my college notes and review the various algorithms as I work on algorithm problems from LeetCode and Cracking the Coding Interview.
This [interviews repository](https://github.com/kdn251/interviews) by Kevin Naughton Jr. served as a quick refresher for me.
@ -57,12 +56,12 @@ Many candidates jump into coding the moment they hear the question. That is usua
Always seek clarification about the question upon hearing it even if it you think it is clear to you. You might discover something that you have missed out and it also sends a signal to the interviewer that you are a careful person who pays attention to details. Some interviewers deliberately omit important details to see if you ask the right questions. Consider asking the following questions:
- How big is the size of the input?
- How big is the range of values?
- What kind of values are there? Are there negative numbers? Floating points? Will there be empty inputs?
- Are there duplicates within the input?
- What are some extreme cases of the input?
- How is the input stored? If you are given a dictionary of words, is it a list of strings or a Trie?
* How big is the size of the input?
* How big is the range of values?
* What kind of values are there? Are there negative numbers? Floating points? Will there be empty inputs?
* Are there duplicates within the input?
* What are some extreme cases of the input?
* How is the input stored? If you are given a dictionary of words, is it a list of strings or a Trie?
After you have sufficiently clarified the scope and intention of the problem, explain your high level approach to the interviewer even if it is a naive solution. If you are stuck, consider various approaches and explain out loud why it will/will not work. Sometimes your interviewer might drop hints and lead you towards the right path.
@ -90,7 +89,7 @@ If there are huge duplicated chunks of code in your solution, it would be a good
Lastly, give the time/space complexity of your code and explain why it is such. You can even annotate certain chunks of your code with the various time/space complexities to demonstrate your understanding of your code and the APIs of your chosen programming language. Explain any trade-offs in your current approach vs alternative approaches, possibly in terms of time/space.
If your interviewer is happy with the solution, the interview usually ends here. It is also not uncommon that the interviewer asks you extension questions, such as how you would handle the problem if the whole input is too large to fit into memory, or if the input arrives as a stream. This is a common follow-up question at Google where they care a lot about scale. The answer is usually a divide-and-conquer approach — perform distributed processing of the data and only read certain chunks of the input from disk into memory, write the output back to disk and combine them later on.
If your interviewer is happy with the solution, the interview usually ends here. It is also not uncommon that the interviewer asks you extension questions, such as how you would handle the problem if the whole input is too large to fit into memory, or if the input arrives as a stream. This is a common follow-up question at Google where they care a lot about scale. The answer is usually a divide-and-conquer approachperform distributed processing of the data and only read certain chunks of the input from disk into memory, write the output back to disk and combine them later on.
### Practicing via Mock Interviews
@ -106,8 +105,7 @@ Personally, I am not that fond of Pramp's approach because if I were to intervie
### Conclusion
Coding interviews are tough. But fortunately, you can get better at them by studying and practicing for them, and doing mock interviews.
To recap, to do well in coding interviews:
Coding interviews are tough. But fortunately, you can get better at them by studying and practicing for them, and doing mock interviews. To recap, to do well in coding interviews:
1. Decide on a programming language
1. Study CS fundamentals

@ -1,5 +1,4 @@
Interview Cheatsheet
==
# Interview Cheatsheet
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.
@ -9,95 +8,95 @@ For a detailed walkthrough of interview preparation, refer to the ["Preparing fo
### 1. Before Interview
|| Things |
|-|-|
|✅|Prepare pen, paper and earphones/headphones.|
|✅|Find a quiet environment with good Internet connection.|
|✅|Ensure webcam and audio are working. There were times I had to restart Chrome to get Hangouts to work again.|
|✅|Request for the option to interview over Hangouts/Skype instead of a phone call; it is easier to send links or text across.|
|✅|Decide on and be familiar with a programming language.|
|✅|Familiarize yourself with the coding environment (CoderPad/CodePen). Set up the coding shortcuts, turn on autocompletion, tab spacing, etc.|
|✅|Prepare answers to the [frequently-asked questions](../non-technical/behavioral.md) in an interview.|
|✅|Prepare some [questions to ask](../non-technical/questions-to-ask.md) at the end of the interview.|
|✅|Dress comfortably. Usually you do not need to wear smart clothes, casual should be fine. T-shirts and jeans are acceptable at most places.|
|✅|Stay calm and composed.|
|⚠️|Turn off the webcam if possible. Most remote interviews will not require video chat and leaving it on only serves as a distraction.|
| | Things |
| --- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| | Prepare pen, paper and earphones/headphones. |
| | Find a quiet environment with good Internet connection. |
| | Ensure webcam and audio are working. There were times I had to restart Chrome to get Hangouts to work again. |
| | Request for the option to interview over Hangouts/Skype instead of a phone call; it is easier to send links or text across. |
| | Decide on and be familiar with a programming language. |
| | Familiarize yourself with the coding environment (CoderPad/CodePen). Set up the coding shortcuts, turn on autocompletion, tab spacing, etc. |
| | Prepare answers to the [frequently-asked questions](../non-technical/behavioral.md) in an interview. |
| | Prepare some [questions to ask](../non-technical/questions-to-ask.md) at the end of the interview. |
| | Dress comfortably. Usually you do not need to wear smart clothes, casual should be fine. T-shirts and jeans are acceptable at most places. |
| | Stay calm and composed. |
| ⚠️ | Turn off the webcam if possible. Most remote interviews will not require video chat and leaving it on only serves as a distraction. |
### 2. Introduction
|| Things |
|-|-|
|✅|Introduce yourself in a few sentences under a minute or two.|
|✅|Mention interesting points that are relevant to the role you are applying for.|
|✅|Sound enthusiastic! Speak with a smile and you will naturally sound more engaging.|
|❌|Spend too long introducing yourself. The more time you spend talking the less time you have to code.|
| | Things |
| --- | ---------------------------------------------------------------------------------------------------- |
| | Introduce yourself in a few sentences under a minute or two. |
| | Mention interesting points that are relevant to the role you are applying for. |
| | Sound enthusiastic! Speak with a smile and you will naturally sound more engaging. |
| | Spend too long introducing yourself. The more time you spend talking the less time you have to code. |
### 3. Upon Getting the Question
|| Things |
|-|-|
|✅|Repeat the question back at the interviewer.|
|✅|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.|
|✅|Clarify input format and range. Ask whether input can be assumed to be well-formed and non-null.|
|✅|Work through a small example to ensure you understood the question.|
|✅|Explain a high level approach even if it is a brute force one.|
|✅|Improve upon the approach and optimize. Reduce duplicated work and cache repeated computations.|
|✅|Think carefully, then state and explain the time and space complexity of your approaches.|
|✅|If stuck, think about related problems you have seen before and how they were solved. Check out the [tips](../algorithms) in this section.|
|❌|Ignore information given to you. Every piece is important.|
|❌|Jump into coding straightaway.|
|❌|Start coding without interviewer's green light.|
|❌|Appear too unsure about your approach or analysis.|
| | Things |
| --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| | Repeat the question back at the interviewer. |
| | 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. |
| | Clarify input format and range. Ask whether input can be assumed to be well-formed and non-null. |
| | Work through a small example to ensure you understood the question. |
| | Explain a high level approach even if it is a brute force one. |
| | Improve upon the approach and optimize. Reduce duplicated work and cache repeated computations. |
| | Think carefully, then state and explain the time and space complexity of your approaches. |
| | If stuck, think about related problems you have seen before and how they were solved. Check out the [tips](../algorithms) in this section. |
| | Ignore information given to you. Every piece is important. |
| | Jump into coding straightaway. |
| | Start coding without interviewer's green light. |
| | Appear too unsure about your approach or analysis. |
### 4. During Coding
|| Things |
|-|-|
|✅|Explain what you are coding/typing to the interviewer, what you are trying to achieve.|
|✅|Practice good coding style. Clear variable names, consistent operator spacing, proper indentation, etc.|
|✅|Type/write at a reasonable speed.|
|✅|As much as possible, write actual compilable code, not pseudocode.|
|✅|Write in a modular fashion. Extract out chunks of repeated code into functions.|
|✅|Ask for permission to use trivial functions without having to implement them; saves you some time.|
|✅|Use the hints given by the interviewer.|
|✅|Demonstrate mastery of your chosen programming language.|
|✅|Demonstrate technical knowledge in data structures and algorithms.|
|✅|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.|
|✅|Practice whiteboard space-management skills.|
|⚠️|Reasonable defensive coding. Check for nulls, empty collections, etc. Can omit if input validity has been clarified with the interviewer.|
|❌|Remain quiet the whole time.|
|❌|Spend too much time writing comments.|
|❌|Use extremely verbose variable names.|
|❌|Copy and paste code without checking.|
|❌|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.|
|❌|Write too big (takes up too much space) or too small (illegible) if on a whiteboard.|
| | Things |
| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| | Explain what you are coding/typing to the interviewer, what you are trying to achieve. |
| | Practice good coding style. Clear variable names, consistent operator spacing, proper indentation, etc. |
| | Type/write at a reasonable speed. |
| | As much as possible, write actual compilable code, not pseudocode. |
| | Write in a modular fashion. Extract out chunks of repeated code into functions. |
| | Ask for permission to use trivial functions without having to implement them; saves you some time. |
| | Use the hints given by the interviewer. |
| | Demonstrate mastery of your chosen programming language. |
| | Demonstrate technical knowledge in data structures and algorithms. |
| | 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. |
| | Practice whiteboard space-management skills. |
| ⚠️ | Reasonable defensive coding. Check for nulls, empty collections, etc. Can omit if input validity has been clarified with the interviewer. |
| | Remain quiet the whole time. |
| | Spend too much time writing comments. |
| | Use extremely verbose variable names. |
| | Copy and paste code without checking. |
| | 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. |
| | Write too big (takes up too much space) or too small (illegible) if on a whiteboard. |
### 5. After Coding
|| Things |
|-|-|
|✅|Scan through your code for mistakes as if it was your first time seeing code written by someone else.|
|✅|Check for off-by-one errors.|
|✅|Come up with more test cases. Try extreme test cases.|
|✅|Step through your code with those test cases.|
|✅|Look out for places where you can refactor.|
|✅|Reiterate the time and space complexity of your code.|
|✅|Explain trade-offs and how the code/approach can be improved if given more time.|
|❌|Immediately announce that you are done coding. Do the above first!|
|❌|Argue with the interviewer. They may be wrong but that is very unlikely given that they are familiar with the question.|
| | Things |
| --- | ----------------------------------------------------------------------------------------------------------------------- |
| | Scan through your code for mistakes as if it was your first time seeing code written by someone else. |
| | Check for off-by-one errors. |
| | Come up with more test cases. Try extreme test cases. |
| | Step through your code with those test cases. |
| | Look out for places where you can refactor. |
| | Reiterate the time and space complexity of your code. |
| | Explain trade-offs and how the code/approach can be improved if given more time. |
| | Immediately announce that you are done coding. Do the above first! |
| | Argue with the interviewer. They may be wrong but that is very unlikely given that they are familiar with the question. |
### 6. Wrap Up
|| Things |
|-|-|
|✅|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).|
|✅|Thank the interviewer.|
|⚠️|Ask about your interview performance. It can get awkward.|
|❌|End the interview without asking any questions.|
| | Things |
| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| | 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). |
| | Thank the interviewer. |
| ⚠️ | Ask about your interview performance. It can get awkward. |
| | End the interview without asking any questions. |
### 7. Post Interview
|| Things |
|-|-|
|✅|Record the interview questions and answers down as these can be useful for future reference.|
|⚠️|Send a follow up email to your interviewer(s) thanking them for their time and the opportunity to interview with them.|
| | Things |
| --- | ---------------------------------------------------------------------------------------------------------------------- |
| | Record the interview questions and answers down as these can be useful for future reference. |
| ⚠️ | Send a follow up email to your interviewer(s) thanking them for their time and the opportunity to interview with them. |

@ -18,10 +18,10 @@ Output: [1, 2, 2]
## Time Complexities
- Bad:
- Time: O((n + m)log(n + m))
- Good:
- Time: O(k)
* Bad:
* Time: O((n + m)log(n + m))
* Good:
* Time: O(k)
## Sample Answers

@ -18,4 +18,4 @@ Given a non-negative integer, find the maximum possible number if you can swap t
## Follow Up
- What if the given integer can be negative?
* What if the given integer can be negative?

@ -1,10 +1,10 @@
// Does not handle negative binary numbers.
function binToInt(binary) {
let res = 0;
for (let i = 0; i < binary.length; i++) {
res = res * 2 + (+binary[i]);
}
return res;
let res = 0;
for (let i = 0; i < binary.length; i++) {
res = res * 2 + +binary[i];
}
return res;
}
console.log(binToInt('0') === parseInt('0', 2) && parseInt('0', 2) === 0);
@ -12,4 +12,7 @@ console.log(binToInt('1') === parseInt('1', 2) && parseInt('1', 2) === 1);
console.log(binToInt('10') === parseInt('10', 2) && parseInt('10', 2) === 2);
console.log(binToInt('11') === parseInt('11', 2) && parseInt('11', 2) === 3);
console.log(binToInt('101') === parseInt('101', 2) && parseInt('101', 2) === 5);
console.log(binToInt('1100011') === parseInt('1100011', 2) && parseInt('1100011', 2) === 99);
console.log(
binToInt('1100011') === parseInt('1100011', 2) &&
parseInt('1100011', 2) === 99,
);

@ -1,18 +1,18 @@
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = left + Math.floor((right - left) / 2);
if (arr[mid] === target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
let left = 0;
let right = arr.length - 1;
while (left <= right) {
const mid = left + Math.floor((right - left) / 2);
if (arr[mid] === target) {
return mid;
}
return -1;
if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
console.log(binarySearch([1, 2, 3, 10], 1) === 0);

@ -1,37 +1,38 @@
function deepEqual(val1, val2) {
if (typeof val1 !== typeof val2) {
if (typeof val1 !== typeof val2) {
return false;
}
// Array comparison.
if (Array.isArray(val1) && Array.isArray(val2)) {
if (val1.length !== val2.length) {
return false;
}
for (let i = 0; i < val1.length; i++) {
if (!deepEqual(val1[i], val2[i])) {
return false;
}
}
return true;
}
// Array comparison.
if (Array.isArray(val1) && Array.isArray(val2)) {
if (val1.length !== val2.length) {
return false;
}
for (let i = 0; i < val1.length; i++) {
if (!deepEqual(val1[i], val2[i])) {
return false;
}
}
return true;
// Object comparison.
if (typeof val1 === 'object' && typeof val2 === 'object' && val1 !== null) {
const keys1 = Object.keys(val1);
const keys2 = Object.keys(val2);
if (keys1.length !== keys2.length) {
return false;
}
// Object comparison.
if (typeof val1 === 'object' && typeof val2 === 'object' && val1 !== null) {
const keys1 = Object.keys(val1), keys2 = Object.keys(val2);
if (keys1.length !== keys2.length) {
return false;
}
for (let i = 0; i < keys1.length; i++) {
if (!deepEqual(val1[keys1[i]], val2[keys2[i]])) {
return false;
}
}
return true;
for (let i = 0; i < keys1.length; i++) {
if (!deepEqual(val1[keys1[i]], val2[keys2[i]])) {
return false;
}
}
return true;
}
// Primitive comparison.
return val1 === val2;
// Primitive comparison.
return val1 === val2;
}
module.exports = deepEqual;

@ -1,35 +1,35 @@
function graphTopoSort(numberNodes, edges) {
const nodes = new Map();
const order = [];
const queue = [];
for (let i = 0; i < numberNodes; i++) {
nodes.set(i, { in: 0, out: new Set() });
}
const nodes = new Map();
const order = [];
const queue = [];
for (let i = 0; i < numberNodes; i++) {
nodes.set(i, {in: 0, out: new Set()});
}
edges.forEach(edge => {
const [node_id, pre_id] = edge;
nodes.get(node_id).in += 1;
nodes.get(pre_id).out.add(node_id);
});
edges.forEach(edge => {
const [node_id, pre_id] = edge;
nodes.get(node_id).in += 1;
nodes.get(pre_id).out.add(node_id);
});
for (let [node_id, value] of nodes.entries()) {
if (value.in === 0) {
queue.push(node_id);
}
for (let [node_id, value] of nodes.entries()) {
if (value.in === 0) {
queue.push(node_id);
}
}
while (queue.length) {
const node_id = queue.shift();
for (let outgoing_id of nodes.get(node_id).out) {
nodes.get(outgoing_id).in -= 1;
if (nodes.get(outgoing_id).in === 0) {
queue.push(outgoing_id);
}
}
order.push(node_id);
while (queue.length) {
const node_id = queue.shift();
for (let outgoing_id of nodes.get(node_id).out) {
nodes.get(outgoing_id).in -= 1;
if (nodes.get(outgoing_id).in === 0) {
queue.push(outgoing_id);
}
}
order.push(node_id);
}
return order.length == numberNodes ? order : [];
return order.length == numberNodes ? order : [];
}
console.log(graphTopoSort(3, [[0, 1], [0, 2]]));

@ -1,19 +1,21 @@
// Does not handle negative numbers.
function intToBin(number) {
if (number === 0) {
return '0';
}
let res = '';
while (number > 0) {
res = String(number % 2) + res;
number = parseInt(number / 2, 10);
}
return res;
if (number === 0) {
return '0';
}
let res = '';
while (number > 0) {
res = String(number % 2) + res;
number = parseInt(number / 2, 10);
}
return res;
}
console.log(intToBin(0) === 0..toString(2) && 0..toString(2) === '0');
console.log(intToBin(1) === 1..toString(2) && 1..toString(2) === '1');
console.log(intToBin(2) === 2..toString(2) && 2..toString(2) === '10');
console.log(intToBin(3) === 3..toString(2) && 3..toString(2) === '11');
console.log(intToBin(5) === 5..toString(2) && 5..toString(2) === '101');
console.log(intToBin(99) === 99..toString(2) && 99..toString(2) === '1100011');
console.log(intToBin(0) === (0).toString(2) && (0).toString(2) === '0');
console.log(intToBin(1) === (1).toString(2) && (1).toString(2) === '1');
console.log(intToBin(2) === (2).toString(2) && (2).toString(2) === '10');
console.log(intToBin(3) === (3).toString(2) && (3).toString(2) === '11');
console.log(intToBin(5) === (5).toString(2) && (5).toString(2) === '101');
console.log(
intToBin(99) === (99).toString(2) && (99).toString(2) === '1100011',
);

@ -1,6 +1,6 @@
// Interval: [start, end].
function intervalsIntersect(a, b) {
return a[0] < b[1] && b[0] < a[1];
return a[0] < b[1] && b[0] < a[1];
}
console.log(intervalsIntersect([1, 2], [3, 4]) === false);

@ -1,7 +1,7 @@
// Interval: [start, end].
// Merges two overlapping intervals into one.
function intervalsMerge(a, b) {
return [Math.min(a[0], b[0]), Math.max(a[1], b[1])];
return [Math.min(a[0], b[0]), Math.max(a[1], b[1])];
}
const deepEqual = require('./deepEqual');

@ -1,14 +1,14 @@
function isSubsequence(s, t) {
if (s.length > t.length) {
return false;
if (s.length > t.length) {
return false;
}
let matchedLength = 0;
for (let i = 0; i < t.length; i++) {
if (matchedLength < s.length && s[matchedLength] === t[i]) {
matchedLength += 1;
}
let matchedLength = 0;
for (let i = 0; i < t.length; i++) {
if (matchedLength < s.length && s[matchedLength] === t[i]) {
matchedLength += 1;
}
}
return matchedLength === s.length;
}
return matchedLength === s.length;
}
console.log(isSubsequence('abc', 'abcde') === true);

@ -1,7 +1,9 @@
function matrixClone(matrix, defaultValue) {
return matrix.map(row => {
return defaultValue === undefined ? row.slice(0) : Array(row.length).fill(defaultValue);
});
return matrix.map(row => {
return defaultValue === undefined
? row.slice(0)
: Array(row.length).fill(defaultValue);
});
}
const deepEqual = require('./deepEqual');
@ -15,4 +17,6 @@ console.log(deepEqual(matrixClone([[1]]), [[1]]));
// Test clone with default value.
console.log(deepEqual(matrixClone([[1, 2], [1, 4]], 1), [[1, 1], [1, 1]]));
console.log(deepEqual(matrixClone([[1, 2], [1, 4]], null), [[null, null], [null, null]]));
console.log(
deepEqual(matrixClone([[1, 2], [1, 4]], null), [[null, null], [null, null]]),
);

@ -1,5 +1,5 @@
function matrixTranspose(matrix) {
return matrix[0].map((col, i) => matrix.map(row => row[i]));
return matrix[0].map((col, i) => matrix.map(row => row[i]));
}
const deepEqual = require('./deepEqual');
@ -7,5 +7,6 @@ const deepEqual = require('./deepEqual');
console.log(deepEqual(matrixTranspose([[1]]), [[1]]));
console.log(deepEqual(matrixTranspose([[1, 2]]), [[1], [2]]));
console.log(deepEqual(matrixTranspose([[1, 2], [1, 4]]), [[1, 1], [2, 4]]));
console.log(deepEqual(matrixTranspose([[1, 2, 3], [4, 5, 6]]), [[1, 4], [2, 5], [3, 6]]));
console.log(
deepEqual(matrixTranspose([[1, 2, 3], [4, 5, 6]]), [[1, 4], [2, 5], [3, 6]]),
);

@ -1,28 +1,30 @@
function traverse(matrix) {
const DIRECTIONS = [[0, 1], [0, -1], [1, 0], [-1, 0]];
const rows = matrix.length, cols = matrix[0].length;
const visited = matrix.map(row => Array(row.length).fill(false));
function dfs(i, j) {
if (visited[i][j]) {
return;
}
visited[i][j] = true;
DIRECTIONS.forEach(dir => {
const row = i + dir[0], col = j + dir[1];
// Boundary check.
if (row < 0 || row >= rows || col < 0 || col >= cols) {
return;
}
// Valid neighbor check.
if (matrix[row][col] !== 1) {
return;
}
dfs(row, col);
});
const DIRECTIONS = [[0, 1], [0, -1], [1, 0], [-1, 0]];
const rows = matrix.length,
cols = matrix[0].length;
const visited = matrix.map(row => Array(row.length).fill(false));
function dfs(i, j) {
if (visited[i][j]) {
return;
}
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
dfs(i, j);
}
visited[i][j] = true;
DIRECTIONS.forEach(dir => {
const row = i + dir[0],
col = j + dir[1];
// Boundary check.
if (row < 0 || row >= rows || col < 0 || col >= cols) {
return;
}
// Valid neighbor check.
if (matrix[row][col] !== 1) {
return;
}
dfs(row, col);
});
}
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
dfs(i, j);
}
}
}

@ -1,60 +1,62 @@
function mergeSort(arr) {
if (arr.length < 2) {
// Arrays of length 0 or 1 are sorted by definition.
return arr;
}
if (arr.length < 2) {
// Arrays of length 0 or 1 are sorted by definition.
return arr;
}
const left = arr.slice(0, Math.floor(arr.length / 2));
const right = arr.slice(Math.floor(arr.length / 2), Math.floor(arr.length));
const left = arr.slice(0, Math.floor(arr.length / 2));
const right = arr.slice(Math.floor(arr.length / 2), Math.floor(arr.length));
return merge(mergeSort(left), mergeSort(right));
return merge(mergeSort(left), mergeSort(right));
}
function merge(arr1, arr2) {
const merged = [];
let i = 0, j = 0;
const merged = [];
let i = 0,
j = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] <= arr2[j]) {
merged.push(arr1[i]);
i++;
} else if (arr2[j] < arr1[i]) {
merged.push(arr2[j]);
j++;
}
while (i < arr1.length && j < arr2.length) {
if (arr1[i] <= arr2[j]) {
merged.push(arr1[i]);
i++;
} else if (arr2[j] < arr1[i]) {
merged.push(arr2[j]);
j++;
}
}
merged.push(...arr1.slice(i), ...arr2.slice(j));
return merged;
merged.push(...arr1.slice(i), ...arr2.slice(j));
return merged;
}
const deepEqual = require('./deepEqual');
console.log(deepEqual(
mergeSort([]),
[],
));
console.log(deepEqual(
mergeSort([1]),
[1],
));
console.log(deepEqual(
mergeSort([2, 1]),
[1, 2],
));
console.log(deepEqual(
mergeSort([7, 2, 4, 3, 1, 2]),
[1, 2, 2, 3, 4, 7],
));
console.log(deepEqual(
mergeSort([1, 2, 3, 4, 5, 0]),
[0, 1, 2, 3, 4, 5],
));
console.log(deepEqual(
mergeSort([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]),
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
));
console.log(deepEqual(
mergeSort([98322, 3242, 876, -234, 34, 12331]),
[-234, 34, 876, 3242, 12331, 98322],
));
console.log(deepEqual(mergeSort([]), []));
console.log(deepEqual(mergeSort([1]), [1]));
console.log(deepEqual(mergeSort([2, 1]), [1, 2]));
console.log(deepEqual(mergeSort([7, 2, 4, 3, 1, 2]), [1, 2, 2, 3, 4, 7]));
console.log(deepEqual(mergeSort([1, 2, 3, 4, 5, 0]), [0, 1, 2, 3, 4, 5]));
console.log(
deepEqual(mergeSort([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]), [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
]),
);
console.log(
deepEqual(mergeSort([98322, 3242, 876, -234, 34, 12331]), [
-234,
34,
876,
3242,
12331,
98322,
]),
);

@ -1,11 +1,13 @@
function treeEqual(node1, node2) {
if (!node1 && !node2) {
return true;
}
if (!node1 || !node2) {
return false;
}
return node1.val == node2.val &&
treeEqual(node1.left, node2.left) &&
treeEqual(node1.right, node2.right);
if (!node1 && !node2) {
return true;
}
if (!node1 || !node2) {
return false;
}
return (
node1.val == node2.val &&
treeEqual(node1.left, node2.left) &&
treeEqual(node1.right, node2.right)
);
}

@ -1,10 +1,10 @@
function treeMirror(node) {
if (!node) {
return;
}
let temp = node.left;
node.left = node.right;
node.right = temp;
treeMirror(node.left);
treeMirror(node.right);
if (!node) {
return;
}
let temp = node.left;
node.left = node.right;
node.right = temp;
treeMirror(node.left);
treeMirror(node.right);
}

Loading…
Cancel
Save