Merge pull request #1 from yangshun/master

Updating to Latest
pull/116/head
avin98 8 years ago committed by GitHub
commit 2f7c42dd5c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -16,42 +16,51 @@
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/format.md) of the top tech companies
- [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 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?
Anybody who wants to land a job at a tech company but is new to technical interviews, or seasoned engineers who have not been on the other side of the interviewing table in a while and wants to get back into the game.
Anybody who wants to land a job at a tech company but is new to technical interviews, seasoned engineers who have not been on the other side of the interviewing table in a while and want to get back into the game, or anyone who wants to be better at technical interviewing.
## How is this repository different?
There are so many awesome books like [Cracking the Coding Interview](http://www.crackingthecodinginterview.com/) and interview-related repositories out there on GitHub, what makes this repository different? The difference is that many existing interview repositories contain mainly links to external resources whereas this repository contains top quality curated content directly for your consumption.
Also, existing resources focus mainly on algorithm questions, and lack in coverage for more domain-specific and non-technical questions. This handbook aims to cover content beyond the typical algorithmic coding questions. 😎
Also, existing resources focus mainly on algorithm questions and lack coverage for more domain-specific and non-technical questions. This handbook aims to cover content beyond the typical algorithmic coding questions. 😎
## 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/format.md)
- [Psychological Tricks](non-technical/psychological.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.
- **[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
If you are interested in how data structures are implemented, check out [Lago](https://github.com/yangshun/lago), a Data Structures and Algorithms library for JavaScript. It is pretty much still WIP but I intend to make it into a library that is able to be used in production and also a reference resource for revising Data Structures and Algorithms.
## Contributing

@ -5,6 +5,8 @@ This section dives deep into practical tips for specific topics of algorithms an
For each topic, study links are recommended to help you master the topic. There is a list of recommended common questions to practice which in my opinion is highly valuable for mastering the core concepts for the topic.
If you are interested in how data structures are implemented, check out [Lago](https://github.com/yangshun/lago), a Data Structures and Algorithms library for JavaScript. It is pretty much still WIP but I intend to make it into a library that is able to be used in production and also a reference resource for revising Data Structures and Algorithms.
## Contents
- [Array](array.md)
@ -27,6 +29,8 @@ For each topic, study links are recommended to help you master the topic. There
## General Tips
Clarify any assumptions you made subconsciously. Many questions are under-specified on purpose.
Always validate input first. Check for invalid/empty/negative/different type input. Never assume you are given the valid parameters. Alternatively, clarify with the interviewer whether you can assume valid input (usually yes), which can save you time from writing code that does input validation.
Are there any time/space complexity requirements/constraints?
@ -56,7 +60,7 @@ Data structures can be augmented to achieve efficient time complexities across d
Hashmaps are probably the most commonly used data structure for algorithm questions. If you are stuck on a question, your last resort can be to enumerate through the possible data structures (thankfully there aren't that many of them) and consider whether each of them can be applied to the problem. This has worked for me sometimes.
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 does not cover all cases.
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.
## Sequence
@ -189,7 +193,7 @@ You can be given a list of edges and tasked to build your own graph from the edg
- Adjacency list.
- Hashmap of hashmaps.
Some inputs look like they are trees but they are actually graphs. In that case you will have to handle cycles and keep a set of visited nodes when traversing.
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:
@ -532,7 +536,7 @@ When a question involves a BST, the interviewer is usually looking for a solutio
#### Study Links
- [Trying to Understand Tries](https://medium.com/basecs/trying-to-understand-tries-3ec6bede0014)
- [Implement Trie (Prefix Tree)]
- [Implement Trie (Prefix Tree)](https://leetcode.com/articles/implement-trie-prefix-tree/)
#### Notes

@ -1,7 +1,7 @@
Arrays
==
- In an arrays 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`.
- 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.
@ -56,3 +56,5 @@ Arrays
- 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.

@ -0,0 +1,7 @@
Bit Manipulation
==
- How do you verify if an interger is a power of 2?
- Wirte 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.

@ -5,8 +5,8 @@ Dynamic Programming
- 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 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.
- Problem reduces to finding the maximum sum of non-consecutive array elements.
- 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
@ -16,7 +16,8 @@ Dynamic Programming
// Dec 6 - 7
// Dec 7 - 12
The answer would be to pick Dec 1-5 (5 days) and then pick Dec 7-12 for a total of 10 days of occupancy, at the same time, leaving at least 1 day gap for cleaning between reservations.
The answer would be to pick Dec 1-5 (5 days) and then pick Dec 7-12 for a total of 10 days of
occupancy, at the same time, leaving at least 1-day gap for cleaning between reservations.
Similarly,
// [3, 6, 4] => 7

@ -10,4 +10,3 @@ 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?
- Implement a LRU cache with O(1) runtime for all its operations.

@ -3,7 +3,7 @@ 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 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,
- 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).

@ -2,3 +2,7 @@ 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?

@ -2,3 +2,4 @@ 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).

@ -6,3 +6,4 @@ Stack
- 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.

@ -4,7 +4,7 @@ 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 special character: `*` (star), `.` (dot), `+` (plus). The star means that there will be zero or more of 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.
- 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`.

@ -67,7 +67,7 @@ The following is a checklist that contains recommendations for implementing HTML
- 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 apperance.
- DO NOT modify the element appearance.
- DO NOT modify element behaviour.
- DO NOT add focusability.
- DO NOT add keyboard event handling.

@ -12,7 +12,3 @@ Talk me through a full stack implementation of an autocomplete widget. A user ca
- 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?
###### References
- https://performancejs.com/post/hde6d32/The-Best-Frontend-JavaScript-Interview-Questions-%28written-by-a-Frontend-Engineer%29

@ -1,12 +1,16 @@
HTML
==
WIP.
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**
## Deprecated Tags
There are a number of tags from past versions of HTML that have become deprecated over time. This means that while they are no longer considered valid elements, most browsers should still be able to read and render them.
## Script Loading
- `<script>` - HTML parsing is blocked, the script is fetched and executed immediately, HTML parsing resumes after the script is executed.

@ -84,6 +84,7 @@ In the back end, the HTML markup will contain `i18n` placeholders and content fo
- Be mindful of how colors are perceived - Colors are perceived differently across languages and cultures. The design should use color appropriately.
- Formatting dates and currencies - Calendar dates are sometimes presented in different ways. Eg. "May 31, 2012" in the U.S. vs. "31 May 2012" in parts of Europe.
- Do not concatenate translated strings - Do not do anything like `"The date today is " + date`. It will break in languages with different word order. Using template parameters instead.
- Language reading direction - In English, we read from left-to-right, top-to-bottom, in traditional Japanese, text is read up-to-down, right-to-left.
###### References
@ -98,6 +99,7 @@ These days, using `data-` attributes is not encouraged. One reason is that users
###### References
- http://html5doctor.com/html5-custom-data-attributes/
- https://www.w3.org/TR/html5/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes
### Consider HTML5 as an open web platform. What are the building blocks of HTML5?
@ -153,7 +155,7 @@ Note: The `async` and `defer` attrib­utes are ignored for scripts that have no
Putting `<link>`s in the head is part of the specification. Besides that, placing at the top allows the page to render progressively which improves user experience. The problem with putting stylesheets near the bottom of the document is that it prohibits progressive rendering in many browsers, including Internet Explorer. Some browsers block rendering to avoid having to repaint elements of the page if their styles change. The user is stuck viewing a blank white page. It prevents the flash of unstyled contents.
**Placing `<scripts>`s just before `<body>`**
**Placing `<script>`s just before `</body>`**
`<script>`s block HTML parsing while they are being downloaded and executed. Downloading the scripts at the bottom will allow the HTML to be parsed and displayed to the user first.
@ -198,6 +200,10 @@ Answers to [Front-end Job Interview Questions - CSS Questions](https://github.co
- **IDs** - Meant to be unique within the document. Can be used to identify an element when linking using a fragment identifier. Elements can only have one `id` attribute.
- **Classes** - Can be reused on multiple elements within the document. Mainly for styling and targeting elements.
###### References
- https://www.w3.org/TR/CSS1/#id-as-selector
- https://www.w3.org/TR/CSS1/#class-as-selector
### What's the difference between "resetting" and "normalizing" CSS? Which would you choose, and why?
- **Resetting** - Resetting is meant to strip all default browser styling on elements. For e.g. `margin`s, `padding`s, `font-size`s of all elements are reset to be the same. You will have to redeclare styling for common typographic elements.
@ -292,6 +298,10 @@ CSS sprites combine multiple images into one single larger image. It is commonly
- Reduce the number of HTTP requests for multiple images (only one single request is required per spritesheet). But with HTTP2, loading multiple images is no longer much of an issue.
- Advance downloading of assets that won't be downloaded until needed, such as images that only appear upon `:hover` pseudo-states. Blinking wouldn't be seen.
###### References
- https://css-tricks.com/css-sprites/
### What are your favorite image replacement techniques and which do you use when?
CSS image replacement is a technique of replacing a text element (usually a header tag like an `<h1>`) with an image (often a logo). It has its origins in the time before web fonts and SVG. For years, web developers battled against browser inconsistencies to craft image replacement techniques that struck the right balance between design and accessibility.
@ -323,10 +333,18 @@ These techniques are related to accessibility (a11y).
- `visibility: hidden`. However the element is still in the flow of the page, and still takes up space.
- `width: 0; height: 0`. Make the element not take up any space on the screen at all, resulting in not showing it.
- `position; absolute; left: -99999px`. Position it outside of the screen.
- `position: absolute; left: -99999px`. Position it outside of the screen.
- `text-indent: -9999px`. This only works on text within the `block` elements.
- Metadata. For example by using Schema.org, RDF and JSON-LD.
- WAI-ARIA. A W3C technical specification that specifies how to increase the accessibility of web pages.
Even if WAI-ARIA is the ideal solution, I would go with the `absolute` positioning approach, as it has the least caveats, works for most elements and it's an easy technique.
I would go with the `absolute` positioning approach, as it has the least caveats and works for most elements.
###### References
- https://www.w3.org/TR/wai-aria-1.1/
- https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA
- http://a11yproject.com/
### Have you ever used a grid system, and if so, what do you prefer?
@ -527,7 +545,7 @@ I would write CSS rules with low specificity so that they can be easily overridd
### What existing CSS frameworks have you used locally, or in production? How would you change/improve them?
- **Bootstrap** - Slow release cycle. Bootstrap 4 has been in alpha for almost 2 years. Add a spinner button component, as it is widely-used.
- **Semantic UI** - Source code structure makes theme customization is extremely hard to understand. Painful to customize with unconventional theming system. Hardcoded config path within the vendor library. Not well-designed for overriding variables unlike in Bootstrap.
- **Semantic UI** - Source code structure makes theme customization extremely hard to understand. Painful to customize with unconventional theming system. Hardcoded config path within the vendor library. Not well-designed for overriding variables unlike in Bootstrap.
- **Bulma** - A lot of non-semantic and superfluous classes and markup required. Not backward compatible. Upgrading versions breaks the app in subtle manners.
### Have you played around with the new CSS Flexbox or Grid specs?
@ -620,7 +638,7 @@ For an in-depth explanation, do check out his [article on Medium](https://codebu
### Explain how prototypal inheritance works
This is an extremely common JavaScript interview question. All JavaScript objects have a `prototype` property, that is a reference to another object. When a property is accessed on an object and if the property is not found on that object, the JavaScript engine looks at the object's `prototype`. and the `prototype`'s `prototype` and so on, until it finds the property defined on one of the `prototype`s or until it reaches the end of the prototype chain. This behaviour simulates classical inheritance, but it is really more of [delegation than inheritance](https://davidwalsh.name/javascript-objects).
This is an extremely common JavaScript interview question. All JavaScript objects have a `prototype` property, that is a reference to another object. When a property is accessed on an object and if the property is not found on that object, the JavaScript engine looks at the object's `prototype`, and the `prototype`'s `prototype` and so on, until it finds the property defined on one of the `prototype`s or until it reaches the end of the prototype chain. This behaviour simulates classical inheritance, but it is really more of [delegation than inheritance](https://davidwalsh.name/javascript-objects).
###### References
@ -675,12 +693,12 @@ console.log(foo == null); // true. Wrong, don't use this to check!
function bar() {}
var baz = bar();
console.log(baz === undefined); // undefined
console.log(baz); // undefined
```
A variable that is `null` will have been explicitly assigned to the `null` value. It represents no value and is different from `undefined` in the sense that it has been explicitly assigned. To check for `null,` simply compare using the strict equality operator. Note that like the above, you should not be using the abstract equality operator (`==`) to check, as it will also return `true` if the value is `undefined`.
```
```js
var foo = null;
console.log(foo === null); // true
@ -712,7 +730,7 @@ A closure is the combination of a function and the lexical environment within wh
They can be used in IIFEs to encapsulate some code within a local scope so that variables declared in it do not leak to the global scope.
```
```js
(function() {
// Some code here.
})();
@ -720,7 +738,7 @@ They can be used in IIFEs to encapsulate some code within a local scope so that
As a callback that is used once and does not need to be used anywhere else. The code will seem more self-contained and readable when handlers are defined right inside the code calling them, rather than having to search elsewhere to find the function body.
```
```js
setTimeout(function () {
console.log('Hello world!');
}, 1000);
@ -728,7 +746,7 @@ setTimeout(function () {
Arguments to functional programming constructs or Lodash (similar to callbacks).
```
```js
const arr = [1, 2, 3];
const double = arr.map(function (el) {
return el * 2;
@ -765,7 +783,7 @@ This question is pretty vague. My best guess at its intention is that it is aski
`var person = Person()` invokes the `Person` as a function, and not as a constructor. Invoking as such is a common mistake if it the function is intended to be used as a constructor. Typically, the constructor does not return anything, hence invoking the constructor like a normal function will return `undefined` and that gets assigned to the variable intended as the instance.
`var person = new Person()` creates an instance of the `Person` object using the `new` operator, which inherits from `Person.prototype`. An alterative would be to use `Object.create`, such as: `Object.create(Person.prototype)`.
`var person = new Person()` creates an instance of the `Person` object using the `new` operator, which inherits from `Person.prototype`. An alternative would be to use `Object.create`, such as: `Object.create(Person.prototype)`.
```js
function Person(name) {
@ -890,7 +908,7 @@ The `XMLHttpRequest` API is frequently used for the asynchronous communication o
JSONP (JSON with Padding) is a method commonly used to bypass the cross-domain policies in web browsers because Ajax requests from the current page to a cross-origin domain is not allowed.
JSONP works by making a request to a cross-origin domain via a `<script>` tag and usually with a `callback` query parameter, for example: `https://example.com?callback=printData`. The server will then wrap the data within the a function called `printData` and return it to the client.
JSONP works by making a request to a cross-origin domain via a `<script>` tag and usually with a `callback` query parameter, for example: `https://example.com?callback=printData`. The server will then wrap the data within a function called `printData` and return it to the client.
```html
<!-- https://mydomain.com -->
@ -922,7 +940,7 @@ These days, [CORS](http://en.wikipedia.org/wiki/Cross-origin_resource_sharing) i
Yes. Handlebars, Underscore, Lodash, AngularJS and JSX. I disliked templating in AngularJS because it made heavy use of strings in the directives and typos would go uncaught. JSX is my new favourite as it is closer to JavaScript and there is barely and syntax to be learnt. Nowadays, you can even use ES2015 template string literals as a quick way for creating templates without relying on third-party code.
```
```js
const template = `<div>My name is: ${name}</div>`;
```
@ -932,7 +950,7 @@ However, do beware of a potential XSS in the above approach as the contents are
Hoisting is a term used to explain the behavior of variable declarations in your code. Variables declared or initialized with the `var` keyword will have their declaration "hoisted" up to the top of the current scope. However, only the declaration is hoisted, the assignment (if there is one), will stay where it is. Let's explain with a few examples.
```
```js
// var declarations are hoisted.
console.log(foo); // undefined
var foo = 1;
@ -946,7 +964,7 @@ console.log(bar); // 2
Function declarations have the body hoisted while the function expressions (written in the form of variable declarations) only has the variable declaration hoisted.
```
```js
// Function Declaration
console.log(foo); // [Function: foo]
foo(); // 'FOOOOO'
@ -972,7 +990,7 @@ When an event triggers on a DOM element, it will attempt to handle the event if
Attributes are defined on the HTML markup but properties are defined on the DOM. To illustrate the difference, imagine we have this text field in our HTML: `<input type="text" value="Hello">`.
```
```js
const input = document.querySelector('input');
console.log(input.getAttribute('value')); // Hello
console.log(input.value); // Hello
@ -980,7 +998,7 @@ console.log(input.value); // Hello
But after you change the value of the text field by adding "World!" to it, this becomes:
```
```js
console.log(input.getAttribute('value')); // Hello
console.log(input.value); // Hello World!
```
@ -1201,7 +1219,7 @@ Practically, ES2015 has vastly improved JavaScript and made it much nicer to wri
- https://softwareengineering.stackexchange.com/questions/72569/what-are-the-pros-and-cons-of-coffeescript
### What tools and techniques do you use debugging JavaScript code?
### What tools and techniques do you use for debugging JavaScript code?
- React and Redux
- [React Devtools](https://github.com/facebook/react-devtools)

@ -12,25 +12,26 @@ WIP.
## Glossary
- **Closure** - TBD
- **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** - TBD
- **Promise** - TBD
- **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 it is used or it's scope. It refers to the object on which a function is being executed and depends entirely on the call-site of the function.
- **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
- https://github.com/getify/You-Dont-Know-JS/blob/master/types%20&%20grammar/README.md#you-dont-know-js-types--grammar
- Reference: [Types and Grammar](https://github.com/getify/You-Dont-Know-JS/blob/master/types%20%26%20grammar/ch1.md)
- Types
- Scopes
- Coercion
- [Coercion](https://github.com/getify/You-Dont-Know-JS/blob/master/up%20%26%20going/ch2.md#coercion)
### Functions
- https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20&%20closures/README.md#you-dont-know-js-scope--closures
- 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`
@ -39,7 +40,7 @@ WIP.
### Prototypes and Objects
- Reference: https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/README.md
- 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/
@ -50,16 +51,17 @@ WIP.
### Async
- Reference: https://github.com/getify/You-Dont-Know-JS/blob/master/async%20&%20performance/README.md#you-dont-know-js-async--performance
- `setTimeout` and `setInterval`
- 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
- [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**
@ -96,7 +98,11 @@ WIP.
- 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/)

@ -0,0 +1,20 @@
Basics
==
## Disclaimer
These items will all change based on your specific company and needs but these items area starting point.
## 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 __?")
## 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?

@ -12,18 +12,23 @@ Learn the [STAR](https://en.wikipedia.org/wiki/Situation,_task,_action,_result)
- Why do you want to work for X company?
- Why do you want to leave your current/last company?
- Tell me about a time where you had a conflict with a co-worker.
- 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
@ -35,6 +40,7 @@ While loving to travel or appreciating Airbnb's growth may be good answers, try
- 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?
@ -87,7 +93,7 @@ Source: [Glassdoor](https://hired.com/blog/candidates/10-top-interview-questions
- 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 where you had a difference of opinion with a team member. How did you handle that?
- 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?
@ -148,7 +154,7 @@ Source: [Glassdoor](https://hired.com/blog/candidates/10-top-interview-questions
Source: [Glassdoor](https://www.glassdoor.com/Interview/Stripe-Interview-Questions-E671932.htm)
- How do you stay up to date with latest technologies?
- 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?

@ -26,6 +26,7 @@ Here are some good questions to ask at the end of the interview, extracted from
- **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?
@ -37,6 +38,7 @@ These questions are suitable for any technical role.
- **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?
@ -46,6 +48,16 @@ These questions are suitable for any technical role.
- 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)
### Management
@ -55,12 +67,14 @@ These questions are suitable for asking Engineering Managers, especially useful
- **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
@ -93,3 +107,4 @@ These questions are intended for senior level management, such as CEO, CTO, VPs.
- [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/)

@ -0,0 +1,147 @@
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)
## How Your Resume is Screened
While many engineers can be rather qualified for the role they are applying for, they miss out on getting a shot at the interview as they might never get past resume screening. The main issue was that they do not understand how recruiters worked.
Before writing your resume, it is important to understand the recruiting structure and how recruiting is done.
### The Skill Set Checklist
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.
Now that I am armed with this list, the search for candidates begin.
Typically, I do not seek that "one perfect candidate". What I seek for is the "best fit candidate". The search is essentially a numbers game. I know that for a specific job posting, there would perhaps be X applicants. At each stage of the interview process, some percentage of the candidates will be eliminated, leaving only a final Y% of the initial pool to choose from. Since Y tends to be a rather small number, recruiters will try to maximize X.
### The 10 Seconds Glance
When I am looking at your resume, I am doing a keyword match against the skill set checklist. If I see a good amount of the right keywords in your resume, it is a pass. If I need to spend more than 10 seconds trying to figure out what you are writing about, it is a fail. If I see an excessive amount of keywords (much looking like spam), it signals a red flag and goes into the "maybe". Depending on whether I think I have enough candidates for the day, you could eventually go into the pass or fail stack.
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 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.
When hiring fresh grads, I know that many of them will not have as much experience as someone who has years of industry experience. Hence, I would look out more for soft skills, such as attention to detail, initiative, passion, ability to get things done, etc. Note: this applies only if you have met the minimum threshold of proficiency/competency in the skill set checklist.
## 10 Ways To Improve Your Resume
Now that you are aware of how recruiters screen your resume, here are 10 actionable ways you can do to improve your resume.
#### 1. Cover letter
I've often received resumes with no cover letters, and I am perfectly fine with it. If you ask me, it is better to have no cover letter than to have a bad cover letter, especially if your cover letter is a "templated" content. An effective cover letter needs to highlight the fit between the job requirements and your skills/experiences. Do not just tell me what you have done in your cover letter; Tell me how it is a fit for what I am looking for.
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.
#### 2. Length of resume
Your resume should be kept to 1 page or a MAXIMUM of 2 pages. Include only your most recent and relevant experiences.
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).
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).
Ideally, keep it short, concise, but as detailed as possible.
#### 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.**
If your GPA is rather low, but you have loads of technical experiences, you can try not listing your GPA in the resume. This kinda "forces" the recruiter to read through your projects/job experience, and perhaps grant you a first interview. If you manage to impress them, who cares about your GPA? But if your GPA is low and you do not have skills for the job... maybe you should work on one of them and revisit job applications later.
In a different scenario, some students have low GPA, but it might be due to some irrelevant classes which they did badly in. E.g. Student X is scoring A for all his programming classes, but did not do well for his language classes. If I am hiring a developer, Student X would still be a suitable candidate despite his low GPA. In such cases, it might even be recommended to attach a transcript along with the resume.
Also, when you list your GPA/results, try to benchmark it. Instead of simply listing 4.6, write 4.6/5.0 (First Class Honors or Summa Cum Laude). To the recruiter, 4.6 does not mean anything if he/she is not familiar with your grading system.
#### 4. Be clear about your objectives
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.
- 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
Always list your resume in reverse chronological order - the most recent at the top. Recruiters are more interested in what you have worked on recently than what you worked on 3 years ago. Chances are, you probably forgot the details too anyway.
#### 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).
#### 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.
#### 8. Listing Your skills
It is useful to list your relevant skills in a quick summary section for easy reading/matching. However, many people make the mistake of listing as many skills/programming languages in the resume as possible. This may get you through the ATS scoring, but it definitely would not leave a good impression on the recruiter - the actual human reading your resume and deciding whether to call you up for an interview!
Ideally, if your resume is good enough, the recruiter should already know what you are proficient in. The skills section is just a quick summary/reiteration. **Listing a bunch of technologies you claim you know without actually showing how you have worked with them is pointless.**
#### 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.
#### 10. Online profile/other interests
Here's the news - Recruiters do search for your name! Definitely pre-empt that by Googling/Facebook-ing/searching yourself on all forms of social media to see what turns up. Make sure your privacy settings are restricted so your online profile shows only the image you are trying to project.
If you have some space on your resume, it is good to list additional interests outside of coding. Eg. skiing, water sports, soccer, etc etc. Gives the interviewer something to talk to you about. It also shows that you are a well-rounded individual/cool person to hang out with.
###### 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)

@ -5,6 +5,23 @@ 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?"
### 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.
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)

@ -21,6 +21,8 @@ This [interviews repository](https://github.com/kdn251/interviews) by Kevin Naug
The Medium publication [basecs](https://medium.com/basecs) by [Vaidehi Joshi](https://medium.com/@vaidehijoshi) is also a great and light-hearted resource to recap on the various data structures and algorithms.
If you are interested in how data structures are implemented, check out [Lago](https://github.com/yangshun/lago), a Data Structures and Algorithms library for JavaScript. It is pretty much still WIP but I intend to make it into a library that is able to be used in production and also a reference resource for revising Data Structures and Algorithms.
### Mastery through Practice
Next, gain familiarity and mastery of the algorithms and data structures in your chosen programming language:
@ -45,11 +47,15 @@ For phone screens/remote interviews, prepare paper and pen/pencil to jot down an
Use earphones and make sure you are in a quiet environment. You definitely do not want to be holding a phone in one hand and only be able to type with the other. Try avoiding using speakers because if the echo is bad, communication is harder and repeating of words will just result in loss of valuable time.
**Self Introduction**
TODO
**Upon Getting the Question**
Many candidates jump into coding the moment they hear the question. That is usually a big mistake. Take a moment to repeat the question back at the interviewer and make sure that you understand exactly what they are asking. If you misunderstood and when you repeat back the question, they will clarify.
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. Consider asking the following questions:
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?
@ -94,4 +100,22 @@ A great resource for practicing mock coding interviews would be [interviewing.io
I have used interviewing.io both as an interviewer and an interviewee and found the experience to be really great! [Aline Lerner](https://twitter.com/alinelernerLLC), the CEO and co-founder of interviewing.io and her team are passionate about revolutionizing the technical interview process and helping candidates to improve their skills at interviewing. She has also published a number of technical interview-related articles on the [interviewing.io blog](http://blog.interviewing.io/). interviewing.io is still in beta now but I recommend signing up as early as possible to increase the likelihood of getting an invite.
Another platform that allows you to practice coding interviews is [Pramp](https://pramp.com/). Where interviewing.io matches potential job seekers with seasoned technical interviewers, Pramp differs takes a different approach. Pramp pairs you up with another peer who is also a job seeker and both of you take turns to assume the role of interviewer and interviewee. Pramp also prepares questions for you, along with suggested solutions and prompts to guide the interviewee. Personally, I do not really like Pramp's approach because if I were to interview someone, I would rather choose a question I am familiar with. Also, many users of the platform do not have the experience of being interviewers and that can result in a horrible interview experience. There was once where my matched peer, as the interviewer, did not have the right understanding of the question and attempted to lead me down the wrong path of solving the question.
Another platform that allows you to practice coding interviews is [Pramp](https://pramp.com/). Where interviewing.io matches potential job seekers with seasoned technical interviewers, Pramp takes a different approach. Pramp pairs you up with another peer who is also a job seeker and both of you take turns to assume the role of interviewer and interviewee. Pramp also prepares questions for you, along with suggested solutions and prompts to guide the interviewee.
Personally, I am not that fond of Pramp's approach because if I were to interview someone, I would rather choose a question I am familiar with. Also, many users of the platform do not have the experience of being interviewers and that can result in a horrible interview experience. There was once where my matched peer, as the interviewer, did not have the right understanding of the question and attempted to lead me down the wrong path of solving the question. However, this is more of a problem of the candidate than the platform though.
### 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:
1. Decide on a programming language
1. Study CS fundamentals
1. Practice solving algorithm questions
1. Internalize the [Do's and Don'ts of interviews](./cheatsheet.md)
1. Practice doing mock interviews
1. Interview successfully to get the job
By following these steps, you will improve your coding interview skills, and be one step closer (or probably more) to landing your dream job.
All the best!

@ -0,0 +1,103 @@
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.
For a detailed walkthrough of interview preparation, refer to the ["Preparing for a Coding Interview"](./) section.
**Legend:** ✅ = Do, ❌ = Don't, ⚠️ = Situational
### 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.|
### 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.|
### 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.|
### 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.|
### 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.|
### 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.|
### 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.|

@ -0,0 +1,15 @@
// 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;
}
console.log(binToInt('0') === parseInt('0', 2) && parseInt('0', 2) === 0);
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);

@ -15,12 +15,12 @@ function binarySearch(arr, target) {
return -1;
}
console.log(binarySearch([1, 2, 3, 10], 1) === 0)
console.log(binarySearch([1, 2, 3, 10], 2) === 1)
console.log(binarySearch([1, 2, 3, 10], 3) === 2)
console.log(binarySearch([1, 2, 3, 10], 10) === 3)
console.log(binarySearch([1, 2, 3, 10], 9) === -1)
console.log(binarySearch([1, 2, 3, 10], 4) === -1)
console.log(binarySearch([1, 2, 3, 10], 0) === -1)
console.log(binarySearch([1, 2, 3, 10], 11) === -1)
console.log(binarySearch([5, 7, 8, 10], 3) === -1)
console.log(binarySearch([1, 2, 3, 10], 1) === 0);
console.log(binarySearch([1, 2, 3, 10], 2) === 1);
console.log(binarySearch([1, 2, 3, 10], 3) === 2);
console.log(binarySearch([1, 2, 3, 10], 10) === 3);
console.log(binarySearch([1, 2, 3, 10], 9) === -1);
console.log(binarySearch([1, 2, 3, 10], 4) === -1);
console.log(binarySearch([1, 2, 3, 10], 0) === -1);
console.log(binarySearch([1, 2, 3, 10], 11) === -1);
console.log(binarySearch([5, 7, 8, 10], 3) === -1);

@ -0,0 +1,37 @@
function deepEqual(val1, 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;
}
// 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;
}
// Primitive comparison.
return val1 === val2;
}
module.exports = deepEqual;

@ -32,4 +32,4 @@ function graphTopoSort(numberNodes, edges) {
return order.length == numberNodes ? order : [];
}
console.log(graphTopoSort(3, [[0, 1], [0, 2]]))
console.log(graphTopoSort(3, [[0, 1], [0, 2]]));

@ -0,0 +1,19 @@
// 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;
}
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');

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

@ -0,0 +1,16 @@
// 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])];
}
const deepEqual = require('./deepEqual');
console.log(deepEqual(intervalsMerge([1, 2], [1, 4]), [1, 4]));
console.log(deepEqual(intervalsMerge([1, 2], [0, 4]), [0, 4]));
console.log(deepEqual(intervalsMerge([1, 2], [0, 2]), [0, 2]));
console.log(deepEqual(intervalsMerge([1, 2], [0, 1.5]), [0, 2]));
console.log(deepEqual(intervalsMerge([1, 4], [1, 2]), [1, 4]));
console.log(deepEqual(intervalsMerge([0, 4], [1, 2]), [0, 4]));
console.log(deepEqual(intervalsMerge([0, 2], [1, 2]), [0, 2]));
console.log(deepEqual(intervalsMerge([0, 1.5], [1, 2]), [0, 2]));

@ -0,0 +1,18 @@
function matrixClone(matrix, defaultValue) {
return matrix.map(row => {
return defaultValue === undefined ? row.slice(0) : Array(row.length).fill(defaultValue);
});
}
const deepEqual = require('./deepEqual');
// Test clone.
const a = [[1, 2], [1, 4]];
console.log(deepEqual(matrixClone(a), [[1, 2], [1, 4]]));
a[0][0] = 4;
console.log(deepEqual(matrixClone(a), [[1, 2], [1, 4]]) === false);
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]]));

@ -0,0 +1,11 @@
function matrixTranspose(matrix) {
return matrix[0].map((col, i) => matrix.map(row => row[i]));
}
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]]));

@ -0,0 +1,28 @@
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);
});
}
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
dfs(i, j);
}
}
}

@ -0,0 +1,60 @@
function mergeSort(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));
return merge(mergeSort(left), mergeSort(right));
}
function merge(arr1, arr2) {
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++;
}
}
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],
));

@ -11,6 +11,32 @@ def binary_search(arr, target):
right = mid - 1
return -1
def bisect_left(arr, target):
"""Returns the leftmost position that `target` should
go to such that the sequence remains sorted."""
left = 0
right = len(arr)
while left < right:
mid = (left + right) // 2
if arr[mid] < target:
left = mid + 1
else:
right = mid
return left
def bisect_right(arr, target):
"""Returns the rightmost position that `target` should
go to such that the sequence remains sorted."""
left = 0
right = len(arr)
while left < right:
mid = (left + right) // 2
if arr[mid] > target:
right = mid
else:
left = mid + 1
return left
print(binary_search([1, 2, 3, 10], 1) == 0)
print(binary_search([1, 2, 3, 10], 2) == 1)
print(binary_search([1, 2, 3, 10], 3) == 2)
@ -20,3 +46,24 @@ print(binary_search([1, 2, 3, 10], 4) == -1)
print(binary_search([1, 2, 3, 10], 0) == -1)
print(binary_search([1, 2, 3, 10], 11) == -1)
print(binary_search([5, 7, 8, 10], 3) == -1)
print(bisect_left([1, 2, 3, 3, 10], 1) == 0)
print(bisect_left([1, 2, 3, 3, 10], 2) == 1)
print(bisect_left([1, 2, 3, 3, 10], 3) == 2) # First "3" is at index 2
print(bisect_left([1, 2, 3, 3, 10], 10) == 4)
# These return a valid index despite target not being in array.
print(bisect_left([1, 2, 3, 3, 10], 9) == 4)
print(bisect_left([1, 2, 3, 3, 10], 0) == 0) # Insert "0" at front
print(bisect_left([1, 2, 3, 3, 10], 11) == 5) # Insert "5" at back
print(bisect_right([1, 2, 3, 3, 10], 1) == 1)
print(bisect_right([1, 2, 3, 3, 10], 2) == 2)
print(bisect_right([1, 2, 3, 3, 10], 3) == 4) # Last "3" is at index 3, so insert new "3" at index 4
print(bisect_right([1, 2, 3, 3, 10], 10) == 5)
# These return a valid index despite target not being in array.
print(bisect_right([1, 2, 3, 3, 10], 9) == 4)
print(bisect_right([1, 2, 3, 3, 10], 0) == 0) # Insert "0" at front
print(bisect_right([1, 2, 3, 3, 10], 11) == 5) # Insert "5" at back

@ -0,0 +1,84 @@
# Implements a min-heap. For max-heap, simply reverse all comparison orders.
#
# Note on alternate subroutine namings (used in some textbooks):
# - _bubble_up = siftdown
# - _bubble_down = siftup
def _bubble_up(heap, i):
while i > 0:
parent_i = (i - 1) // 2
if heap[i] < heap[parent_i]:
heap[i], heap[parent_i] = heap[parent_i], heap[i]
i = parent_i
continue
break
def _bubble_down(heap, i):
startpos = i
newitem = heap[i]
left_i = 2 * i + 1
while left_i < len(heap):
# Pick the smaller of the L and R children
right_i = left_i + 1
if right_i < len(heap) and not heap[left_i] < heap[right_i]:
child_i = right_i
else:
child_i = left_i
# Break if heap invariant satisfied
if heap[i] < heap[child_i]:
break
# Move the smaller child up.
heap[i], heap[child_i] = heap[child_i], heap[i]
i = child_i
left_i = 2 * i + 1
def heapify(lst):
for i in reversed(range(len(lst) // 2)):
_bubble_down(lst, i)
def heappush(heap, item):
heap.append(item)
_bubble_up(heap, len(heap) - 1)
def heappop(heap):
if len(heap) == 1:
return heap.pop()
min_value = heap[0]
heap[0] = heap[-1]
del heap[-1]
_bubble_down(heap, 0)
return min_value
# Example usage
heap = [3, 2, 1, 0]
heapify(heap)
print('Heap(0, 1, 2, 3):', heap)
heappush(heap, 4)
heappush(heap, 7)
heappush(heap, 6)
heappush(heap, 5)
print('Heap(0, 1, 2, 3, 4, 5, 6, 7):', heap)
sorted_list = [heappop(heap) for _ in range(8)]
print('Heap-sorted list:', sorted_list)
# Large test case, for randomized tests
import random
# Heapify 0 ~ 99
heap = list(range(100))
random.shuffle(heap)
heapify(heap)
# Push 100 ~ 199 in random order
new_elems = list(range(100, 200))
random.shuffle(new_elems)
for elem in new_elems:
heappush(heap, elem)
sorted_list = [heappop(heap) for _ in range(200)]
print(sorted_list == sorted(sorted_list))

@ -0,0 +1,109 @@
# Singly-Linked List
#
# The linked list is passed around as a variable pointing to the
# root node of the linked list, or None if the list is empty.
class LinkedListNode:
def __init__(self, value):
self.value = value
self.next = None
def linked_list_append(linked_list, value):
'''Appends a value to the end of the linked list'''
node = linked_list
insert_node = LinkedListNode(value)
if not node:
return insert_node
while node.next:
node = node.next
node.next = insert_node
return linked_list
def linked_list_insert_index(linked_list, value, index):
'''Inserts a value at a particular index'''
node = linked_list
insert_node = LinkedListNode(value)
# Check if inserting at head
if index == 0:
insert_node.next = node
return insert_node
# Skip ahead
for _ in range(index - 1):
node = node.next
if not node:
raise ValueError
insert_node.next = node.next
node.next = insert_node
return linked_list
def linked_list_delete(linked_list, value):
'''Deletes the first occurrence of a value in the linked list'''
node = linked_list
# Check if deleting at head
if node.value == value:
return node.next
# Skip ahead
while node.next:
if node.next.value == value:
node.next = node.next.next
return linked_list
node = node.next
raise ValueError
def linked_list_delete_index(linked_list, index):
'''Deletes the element at a particular index in the linked list'''
node = linked_list
# Check if deleting at head
if index == 0:
return node.next
# Skip ahead
for _ in range(index - 1):
node = node.next
if not node:
raise ValueError
if not node.next:
raise ValueError
node.next = node.next.next
return linked_list
def linked_list_iter(linked_list):
'''Lazy iterator over each node in the linked list'''
node = linked_list
while node is not None:
yield node
node = node.next
# Append to back
linked_list = None # Start with an empty linked list
linked_list = linked_list_append(linked_list, 1)
linked_list = linked_list_append(linked_list, 2)
linked_list = linked_list_append(linked_list, 4)
print([node.value for node in linked_list_iter(linked_list)])
# Insert by index
linked_list = linked_list_insert_index(linked_list, 0, 0) # Front
print([node.value for node in linked_list_iter(linked_list)])
linked_list = linked_list_insert_index(linked_list, 3, 3) # Back
print([node.value for node in linked_list_iter(linked_list)])
# Delete "3"
linked_list = linked_list_delete(linked_list, 3)
print([node.value for node in linked_list_iter(linked_list)])
# Delete by index
linked_list = linked_list_delete_index(linked_list, 0)
print([node.value for node in linked_list_iter(linked_list)])
linked_list = linked_list_delete_index(linked_list, 1)
print([node.value for node in linked_list_iter(linked_list)])
# Delete until empty
linked_list = linked_list_delete_index(linked_list, 0)
linked_list = linked_list_delete_index(linked_list, 0)
print([node.value for node in linked_list_iter(linked_list)])

@ -0,0 +1,60 @@
## QuickSelect -- Linear-time k-th order statistic
## (i.e. select the k-th smallest element in an unsorted array)
## https://en.wikipedia.org/wiki/Quickselect
def partition(array, start, end, pivot):
"""Partitions by a pivot value, which might not necessarily be in the array.
This variant is useful when you want to bound your recursion depth by the
range of the input values, and not the length of the array."""
pivot_index = start
for i in range(start, end):
if array[i] <= pivot:
array[i], array[pivot_index] = array[pivot_index], array[i]
pivot_index += 1
return pivot_index
import random
def partition_first(array, start, end):
"""Selects the first element as pivot. Returns the index where the pivot went to.
In this variant, we can guarantee that the pivot will be in its final sorted position.
We need this guarantee for QuickSelect."""
if start + 1 == end:
return start
pivot = array[start]
pivot_index = start + 1
for i in range(start + 1, end):
if array[i] <= pivot:
array[i], array[pivot_index] = array[pivot_index], array[i]
pivot_index += 1
# Move pivot to front
array[start], array[pivot_index - 1] = array[pivot_index - 1], array[start]
return pivot_index - 1
def quick_select(array, k):
"""NOTE: k-th smallest element counts from 0!"""
left = 0
right = len(array)
while True:
random_index = random.sample(range(left, right), 1)[0]
array[left], array[random_index] = array[random_index], array[left]
pivot_index = partition_first(array, left, right)
if k == pivot_index:
return array[pivot_index]
if k < pivot_index:
right = pivot_index
else:
left = pivot_index + 1
print(quick_select([0], 0) == 0)
print(quick_select([0, 1, 2, 3, 4], 2) == 2)
print(quick_select([4, 3, 2, 1, 0], 2) == 2)
print(quick_select([1, 3, 4, 2, 0], 2) == 2)
# Large test case, for randomized tests
lst = list(range(1000))
for _ in range(10):
k = random.randint(0, 999)
random.shuffle(lst)
print(quick_select(lst, k) == k)

@ -0,0 +1,41 @@
## Rabin-Karp Rolling Hash
## Implementation of: https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm#Hash_function_used
##
## This rolling hash function is useful when you need to compute the hash of successive substrings
## of text. E.g. note that going from 'abcd' to 'bcde', we drop the 'a' from the back and add an 'e'
## on the right. The rolling hash function thus allows us to update the hash in-place O(1) instead of
## recomputing the full hash of the substring O(m), where m is the length of the substring.
##
## NOTE: The implementation below takes in a tuple of integers, to be as general as possible. For use
## with strings, simply take the ASCII value of each character before passing into the functions.
BASE = 101 # Arbitrary prime number
def rk_hash_init(tpl):
'''Initializes the hash with a tuple of integers.'''
return sum(n * BASE ** i for i, n in enumerate(reversed(tpl)))
def rk_hash_update(curr_hash, size, add_n, rem_n):
'''Updates the hash by removing an integer from the left and appending
an integer to the right.
curr_hash: The previous hash
size: The size of the rolling window
add_n: The integer appended to the right
rem_n: The integer removed from the left'''
return (curr_hash - (rem_n * BASE ** (size - 1))) * BASE + add_n
abc_hash = rk_hash_init(tuple(map(ord, 'abc'))) # Init the hash with 'abc'
print('abc:', abc_hash)
bcd_hash_1 = rk_hash_update(abc_hash, 3, ord('d'), ord('a')) # Add a 'd' to the right, remove an 'a' from the left
print('bcd 1:', bcd_hash_1)
zbc_hash = rk_hash_init(tuple(map(ord, 'zbc'))) # Init the hash with 'zbc'
print('zbc:', zbc_hash)
bcd_hash_2 = rk_hash_update(zbc_hash, 3, ord('d'), ord('z')) # Add a 'd' to the right, remove a 'z' from the left
print('bcd 2:', bcd_hash_2)
# Notice that both hash values are the same despite arriving via different paths
print(bcd_hash_1 == bcd_hash_2)

@ -0,0 +1,50 @@
## Union-Find data structure
## https://en.wikipedia.org/wiki/Disjoint-set_data_structure
parents = [0, 1, 2, 3, 4, 5, 6] # parent[i] is the parent of i
weights = [1, 1, 1, 1, 1, 1, 1]
def find_root(parents, p):
'''Average: O(log n)'''
root = p
while parents[root] != root:
root = parents[root]
# Flatten tree
while parents[p] != p:
parents[p], p = root, parents[p]
return root
def union(parents, p, q):
'''Average: O(log n)'''
p = find_root(parents, p)
q = find_root(parents, q)
# Link the smaller node to the larger node
if weights[p] > weights[q]:
parents[q] = p
weights[p] += weights[q]
else:
parents[p] = q
weights[q] += weights[p]
# Start with all elements separate
# -> [0], [1], [2], [3], [4], [5], [6]
print(find_root(parents, 2) == 2)
# Merge 1, 2, 3 and 4, 5, 6
# -> [0], [1, 2, 3], [4, 5, 6]
union(parents, 1, 2)
union(parents, 2, 3)
union(parents, 4, 5)
union(parents, 4, 6)
# Roots of 1, 2, 3 and 4, 5, 6 are the same
print(find_root(parents, 0))
print(list(find_root(parents, i) for i in (1, 2, 3)))
print(list(find_root(parents, i) for i in (4, 5, 6)))
# Merge 2, 4
# -> [0], [1, 2, 3, 4, 5, 6]
union(parents, 2, 4)
print(list(find_root(parents, i) for i in (1, 2, 3, 4, 5, 6)))
Loading…
Cancel
Save