Merge pull request #1 from yangshun/master

Update fork
pull/179/head
Quan Yang 5 years ago committed by GitHub
commit 43b7026c29
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -8,4 +8,4 @@ trim_trailing_whitespace = true
[*.{js,py}]
charset = utf-8
indent_style = space
indent_size = 4
indent_size = 2

@ -0,0 +1,3 @@
github: [yangshun]
open_collective: tech-interview-handbook
custom: https://www.buymeacoffee.com/yangshun

@ -0,0 +1,8 @@
tasks:
- command: gp await-port 3000 && gp preview $(gp url 3000)/tech-interview-handbook/
- before: cd website/
init: yarn install
command: yarn start
ports:
- port: 3000
onOpen: ignore

@ -0,0 +1,8 @@
{
"bracketSpacing": false,
"jsxBracketSameLine": true,
"printWidth": 80,
"proseWrap": "never",
"singleQuote": true,
"trailingComma": "all"
}

@ -1,46 +1,3 @@
# Contributor Covenant Code of Conduct
# Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at tay.yang.shun@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
We have adopted the same Code of Conduct as Facebook that we expect project participants to adhere to. Please read [the full text](https://code.facebook.com/codeofconduct) so that you can understand what actions will and will not be tolerated.

@ -0,0 +1,7 @@
## Contributing
When contributing to this repository, if it is a non-trivial change, please first discuss the change you wish to make via creating an issue in this repository.
As much as possible, try to follow the existing format of markdown and code. JavaScript code should adopt [Standard style](https://standardjs.com/).
Please note we have a Code of Conduct, please follow it in all your interactions with the project.

@ -1,6 +1,6 @@
MIT License
Copyright (c) 2017 Tay Yang Shun
Copyright (c) 2017-Present Yangshun Tay
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

@ -1,62 +1,74 @@
<h1 align="center">Tech Interview Handbook</h1>
<div align="center">
<a href="https://dribbble.com/shots/3831443-Tech-Interview-Handbook">
<img src="https://cdn.rawgit.com/yangshun/tech-interview-handbook/master/assets/book.svg" alt="Tech Interview Handbook" width="400"/>
</a>
<a href="https://yangshun.github.io/tech-interview-handbook/">
<img src="website/static/img/logo.svg" alt="Tech Interview Handbook" width="400">
</a>
<br>
<a href="https://gitpod.io/#https://github.com/yangshun/tech-interview-handbook">
<img src="https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod" alt="Gitpod Ready to Code">
</a>
<br>
<p>
<em>Credits: <a href="https://dribbble.com/shots/3831443-Tech-Interview-Handbook">Illustration</a> by <a href="https://dribbble.com/yangheng">@yangheng</a>
</em>
<em>Credits: <a href="https://dribbble.com/shots/3831443-Tech-Interview-Handbook">Illustration</a> by <a href="https://dribbble.com/leftaligned">@leftaligned</a></em>
</p>
<h3>
<a href="https://yangshun.github.io/tech-interview-handbook/">Read on the website</a>
</h3>
</div>
<hr/>
<h3 align="center">
Black Lives Matter. <a href="https://support.eji.org/give/153413/#!/donation/checkout" target="_blank">Support the Equal Justice Initiative</a>
</h3>
<hr/>
## What is this?
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:
Carefully curated content to help you ace your next technical interview, with a focus on algorithms. System design questions are in-progress. Besides the usual algorithm questions, other **awesome** stuff includes:
- [How to prepare](preparing) for coding interviews
- [Interview Cheatsheet](preparing/cheatsheet.md) - Straight-to-the-point Do's and Don'ts 🆕
- [Algorithm tips and the best practice questions](algorithms) categorized by topic
- ["Front-end Job Interview Questions" answers](front-end/interview-questions.md)
- [Interview formats](non-technical/interview-formats.md) of the top tech companies
- [Behavioral questions](non-technical/behavioral.md) categorized by companies
- [Good questions to ask your interviewers](non-technical/questions-to-ask.md) at the end of the interviews
- [Helpful resume tips](non-technical/resume.md) to get your resume noticed and the Do's and Don'ts
- [How to prepare](https://yangshun.github.io/tech-interview-handbook/coding-round-overview) for coding interviews
- [Interview Cheatsheet](https://yangshun.github.io/tech-interview-handbook/cheatsheet) - Straight-to-the-point Do's and Don'ts
- [Algorithm tips and the best practice questions](https://yangshun.github.io/tech-interview-handbook/algorithms/algorithms-introduction) categorized by topic
- ["Front-end Job Interview Questions" answers](https://github.com/yangshun/front-end-interview-handbook)
- [Interview formats](https://yangshun.github.io/tech-interview-handbook/interview-formats) of the top tech companies
- [Behavioral questions](https://yangshun.github.io/tech-interview-handbook/behavioral-questions) asked by the top tech companies
- [Good questions to ask your interviewers](https://yangshun.github.io/tech-interview-handbook/questions-to-ask) at the end of the interviews
- [Helpful resume tips](https://yangshun.github.io/tech-interview-handbook/resume) 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!
Help from you in contributing content would be very much appreciated!
## Why do I want this?
This repository has *practical* content that covers all phases of a technical interview; from applying for a job to passing the interviews to offer negotiation. Technically competent candidates might still find the non-technical content helpful as well.
This repository has _practical_ content that covers all phases of a technical interview, from applying for a job to passing the interviews to offer negotiation. Technically competent candidates might still find the non-technical content helpful as well.
## Who is this for?
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.
---
<div align="center">
<strong>💰 Looking for a job? Sign up for free with <a href="https://triplebyte.com/a/PJaJNpO/tihg">Triplebyte</a> to efficiently interview with top tech companies! 💰</strong>
</div>
---
## 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.
There are 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 coverage for more domain-specific and non-technical questions. This handbook aims to cover content beyond the typical algorithmic coding questions. 😎
## Looking for Front End content?
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. 😎
Front end-related content have been extracted out into a separate repository - [Front End Interview Handbook](https://github.com/yangshun/front-end-interview-handbook).
## Contents
- **[Preparing for a Coding Interview](preparing)**
- [Interview cheatsheet](preparing/cheatsheet.md) - Straight-to-the-point Do's and Don'ts
- **[Algorithm Questions](algorithms)** - Questions categorized by topics
- **[Design Questions](design)**
- **[Front-end Study Notes](front-end)** - Summarized notes on the various aspects of front-end
- [Front-end Job Interview Questions and Answers](front-end/interview-questions.md) 🔥⭐
- **[Non-Technical Tips](non-technical)** - Random non-technical tips that cover behavioral and psychological aspects, interview formats and "Do you have any questions for me?"
- [Resume Tips](non-technical/resume.md)
- [Behavioral Questions](non-technical/behavioral.md)
- [Interview Formats](non-technical/interview-formats.md)
- [Psychological Tricks](non-technical/psychological-tricks.md)
- [Questions to Ask](non-technical/questions-to-ask.md)
- [Negotiation Tips](non-technical/negotiation.md)
- **[Utilities](utilities)** - Snippets of algorithms/code that will help in coding questions
- **UPDATE** - Check out [Lago](https://github.com/yangshun/lago), which is a Data Structures and Algorithms library that contains more high-quality implementations with 100% test coverage.
A [Docusaurus](https://github.com/facebook/docusaurus) website has been created to provide a better reading experience. Check out the website [here](https://yangshun.github.io/tech-interview-handbook/)!
## Related
@ -66,7 +78,41 @@ If you are interested in how data structures are implemented, check out [Lago](h
There are no formal contributing guidelines at the moment as things are still in flux and we might find a better approach to structure content as we go along. You are welcome to contribute whatever you think will be helpful to fellow engineers. If you would like to contribute content for different domains, feel free to create an issue or submit a pull request and we can discuss further.
### Online one-click setup for contributing
You can use Gitpod (A free online VS Code-like IDE) for contributing online. With a single click it will launch a workspace and automatically:
- clone the tech-interview-handbook repo.
- install the dependencies.
- run `yarn start`.
So that you can start straight away.
[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/yangshun/tech-interview-handbook)
### Contributors
This project exists thanks to all the people who contributed. [[Contribute](CONTRIBUTING.md)]. <a href="https://github.com/yangshun/tech-interview-handbook/graphs/contributors"><img src="https://opencollective.com/tech-interview-handbook/contributors.svg?width=890&button=false"></a>
### Backers
Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/tech-interview-handbook#backer)]
<a href="https://opencollective.com/tech-interview-handbook#backers" target="_blank"><img src="https://opencollective.com/tech-interview-handbook/backers.svg?width=890"></a>
<a href="https://www.buymeacoffee.com/yangshun" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png" alt="Buy Me A Coffee" style="height: auto !important; width: auto !important;"></a>
### Sponsors
Support this project by becoming a sponsor. Your logo/profile picture will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/tech-interview-handbook#sponsor)]
<a href="https://opencollective.com/tech-interview-handbook/sponsor/0/website" target="_blank"><img src="https://opencollective.com/tech-interview-handbook/sponsor/0/avatar.svg"></a> <a href="https://opencollective.com/tech-interview-handbook/sponsor/1/website" target="_blank"><img src="https://opencollective.com/tech-interview-handbook/sponsor/1/avatar.svg"></a> <a href="https://opencollective.com/tech-interview-handbook/sponsor/2/website" target="_blank"><img src="https://opencollective.com/tech-interview-handbook/sponsor/2/avatar.svg"></a> <a href="https://opencollective.com/tech-interview-handbook/sponsor/3/website" target="_blank"><img src="https://opencollective.com/tech-interview-handbook/sponsor/3/avatar.svg"></a> <a href="https://opencollective.com/tech-interview-handbook/sponsor/4/website" target="_blank"><img src="https://opencollective.com/tech-interview-handbook/sponsor/4/avatar.svg"></a> <a href="https://opencollective.com/tech-interview-handbook/sponsor/5/website" target="_blank"><img src="https://opencollective.com/tech-interview-handbook/sponsor/5/avatar.svg"></a> <a href="https://opencollective.com/tech-interview-handbook/sponsor/6/website" target="_blank"><img src="https://opencollective.com/tech-interview-handbook/sponsor/6/avatar.svg"></a> <a href="https://opencollective.com/tech-interview-handbook/sponsor/7/website" target="_blank"><img src="https://opencollective.com/tech-interview-handbook/sponsor/7/avatar.svg"></a> <a href="https://opencollective.com/tech-interview-handbook/sponsor/8/website" target="_blank"><img src="https://opencollective.com/tech-interview-handbook/sponsor/8/avatar.svg"></a> <a href="https://opencollective.com/tech-interview-handbook/sponsor/9/website" target="_blank"><img src="https://opencollective.com/tech-interview-handbook/sponsor/9/avatar.svg"></a>
## Maintainers
- [Yangshun Tay](https://github.com/yangshun)
- [Louie Tan](https://github.com/louietyj)
## Disclaimer
I am providing code in the repository to you under an open source license. Because this is my personal repository, the license you receive to my code is from me and not my employer (Facebook)

@ -1,578 +1,5 @@
Algorithm Questions
==
# Algorithms
This section dives deep into practical tips for specific topics of algorithms and data structures which appear frequently in coding questions. Many algorithm questions involve techniques that can be applied to questions of similar nature. The more techniques you have in your arsenal, the higher the chances of passing the interview. They may lead you to discover corner cases you might have missed out or even lead you towards the optimal approach!
The contents have been moved to the [website](https://yangshun.github.io/tech-interview-handbook/algorithms/algorithms-introduction).
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)
- [Dynamic Programming and Memoization](dynamic-programming.md)
- [Geometry](geometry.md)
- [Graph](graph.md)
- [Hash Table](hash-table.md)
- [Heap](heap.md)
- [Interval](interval.md)
- [Linked List](linked-list.md)
- [Math](math.md)
- [Matrix](matrix.md)
- [Object-Oriented Programming](oop.md)
- [Permutation](permutation.md)
- [Queue](queue.md)
- [Sorting and Searching](sorting-searching.md)
- [Stack](stack.md)
- [String](string.md)
- [Tree](tree.md)
## General Tips
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?
Check for off-by-one errors.
In languages where there are no automatic type coercion, check that concatenation of values are of the same type: `int`/`str`/`list`.
After finishing your code, use a few example inputs to test your solution.
Is the algorithm meant to be run multiple times, for example in a web server? If yes, the input is likely to be preprocess-able to improve the efficiency in each call.
Use a mix of functional and imperative programming paradigms:
- Write pure functions as much as possible.
- Pure functions are easier to reason about and can help to reduce bugs in your implementation.
- Avoid mutating the parameters passed into your function especially if they are passed by reference unless you are sure of what you are doing.
- However, functional programming is usually expensive in terms of space complexity because of non-mutation and the repeated allocation of new objects. On the other hand, imperative code is faster because you operate on existing objects. Hence you will need to achieve a balance between accuracy vs efficiency, by using the right amount of functional and imperative code where appropriate.
- Avoid relying on and mutating global variables. Global variables introduce state.
- If you have to rely on global variables, make sure that you do not mutate it by accident.
Generally, to improve the speed of a program, we can either choose a more appropriate data structure/algorithm or use more memory. It's a classic space/time tradeoff.
Data structures are your weapons. Choosing the right weapon for the right battle is the key to victory. Be very familiar about the strengths of each data structure and the time complexities for its various operations.
Data structures can be augmented to achieve efficient time complexities across different operations. For example, a hash map can be used together with a doubly-linked list to achieve O(1) time complexity for both the `get` and `put` operation in an [LRU cache](https://leetcode.com/problems/lru-cache/).
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 may not cover all cases.
## Sequence
#### Notes
Arrays and strings are considered sequences (a string is a sequence of characters). There are tips relevant for dealing with both arrays and strings which will be covered here.
Are there duplicate values in the sequence, would it affect the answer?
Check for sequence out of bounds.
Be mindful about slicing or concatenating sequences in your code. Typically, slicing and concatenating sequences require O(n) time. Use start and end indices to demarcate a subarray/substring where possible.
Sometimes you can traverse the sequence from the right rather than from the left.
Master the [sliding window technique](https://discuss.leetcode.com/topic/30941/here-is-a-10-line-template-that-can-solve-most-substring-problems) that applies to many substring/subarray problems.
When you are given two sequences to process, it is common to have one index per sequence to traverse/compare the both of them. For example, we use the same approach to merge two sorted arrays.
#### Corner Cases
- Empty sequence.
- Sequence with 1 or 2 elements.
- Sequence with repeated elements.
## Array
#### Notes
Is the array sorted or partially sorted? If it is, some form of binary search should be possible. This also usually means that the interviewer is looking for a solution that is faster than O(n).
Can you sort the array? Sometimes sorting the array first may significantly simplify the problem. Make sure that the order of array elements do not need to be preserved before attempting a sort.
For questions where summation or multiplication of a subarray is involved, pre-computation using hashing or a prefix/suffix sum/product might be useful.
If you are given a sequence and the interviewer asks for O(1) space, it might be possible to use the array itself as a hash table. For example, if the array only has values from 1 to N, where N is the length of the array, negate the value at that index (minus one) to indicate presence of that number.
#### Practice Questions
- [Two Sum](https://leetcode.com/problems/two-sum/)
- [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)
- [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/)
- [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/)
- [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/)
- [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/)
- [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/)
- [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/)
- [3Sum](https://leetcode.com/problems/3sum/)
- [Container With Most Water](https://leetcode.com/problems/container-with-most-water/)
## Binary
#### Study Links
- [Bits, Bytes, Building With Binary](https://medium.com/basecs/bits-bytes-building-with-binary-13cb4289aafa)
#### Notes
Questions involving binary representations and bitwise operations are asked sometimes and you must be absolutely familiar with how to convert a number from decimal form into binary form (and vice versa) in your chosen programming language.
Some helpful utility snippets:
- Test k<sup>th</sup> bit is set: `num & (1 << k) != 0`.
- Set k<sup>th</sup> bit: `num |= (1 << k)`.
- Turn off k<sup>th</sup> bit: `num &= ~(1 << k)`.
- Toggle the k<sup>th</sup> bit: `num ^= (1 << k)`.
- To check if a number is a power of 2, `num & num - 1 == 0`.
#### Corner Cases
- Check for overflow/underflow.
- Negative numbers.
#### Practice Questions
- [Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/)
- [Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/)
- [Counting Bits](https://leetcode.com/problems/counting-bits/)
- [Missing Number](https://leetcode.com/problems/missing-number/)
- [Reverse Bits](https://leetcode.com/problems/reverse-bits/)
## Dynamic Programming
#### Study Links
- [Demystifying Dynamic Programming](https://medium.freecodecamp.org/demystifying-dynamic-programming-3efafb8d4296)
#### Notes
Dynamic Programming (DP) is usually used to solve optimization problems. The only way to get better at DP is to practice. It takes some amount of practice to be able to recognize that a problem can be solved by DP.
Sometimes you do not need to store the whole DP table in memory, the last two values or the last two rows of the matrix will suffice.
#### Practice Questions
- 0/1 Knapsack
- [Climbing Stairs](https://leetcode.com/problems/climbing-stairs/)
- [Coin Change](https://leetcode.com/problems/coin-change/)
- [Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/)
- [Longest Common Subsequence]()
- [Word Break Problem](https://leetcode.com/problems/word-break/)
- [Combination Sum](https://leetcode.com/problems/combination-sum-iv/)
- [House Robber](https://leetcode.com/problems/house-robber/) and [House Robber II](https://leetcode.com/problems/house-robber-ii/)
- [Decode Ways](https://leetcode.com/problems/decode-ways/)
- [Unique Paths](https://leetcode.com/problems/unique-paths/)
- [Jump Game](https://leetcode.com/problems/jump-game/)
## Geometry
#### Notes
When comparing euclidean distance between two pairs of points, using dx<sup>2</sup> + dy<sup>2</sup> is sufficient. It is unnecessary to square root the value.
To find out if two circles overlap, check that the distance between the two centers of the circles is less than the sum of their radii.
## Graph
#### Study Links
- [From Theory To Practice: Representing Graphs](https://medium.com/basecs/from-theory-to-practice-representing-graphs-cfd782c5be38)
- [Deep Dive Through A Graph: DFS Traversal](https://medium.com/basecs/deep-dive-through-a-graph-dfs-traversal-8177df5d0f13)
- [Going Broad In A Graph: BFS Traversal](https://medium.com/basecs/going-broad-in-a-graph-bfs-traversal-959bd1a09255)
#### Notes
Be familiar with the various graph representations, graph search algorithms and their time and space complexities.
You can be given a list of edges and tasked to build your own graph from the edges to perform a traversal on. The common graph representations are:
- Adjacency matrix.
- Adjacency list.
- Hashmap of hashmaps.
A tree-like diagram could very well be a graph that allows for cycles and a naive recursive solution would not work. In that case you will have to handle cycles and keep a set of visited nodes when traversing.
#### Graph search algorithms:
- **Common** - Breadth-first Search, Depth-first Search
- **Uncommon** - Topological Sort, Dijkstra's algorithm
- **Rare** - Bellman-Ford algorithm, Floyd-Warshall algorithm, Prim's algorithm, Kruskal's algorithm
In coding interviews, graphs are commonly represented as 2-D matrices where cells are the nodes and each cell can traverse to its adjacent cells (up/down/left/right). Hence it is important that you be familiar with traversing a 2-D matrix. When recursively traversing the matrix, always ensure that your next position is within the boundary of the matrix. More tips for doing depth-first searches on a matrix can be found [here](https://discuss.leetcode.com/topic/66065/python-dfs-bests-85-tips-for-all-dfs-in-matrix-question/). A simple template for doing depth-first searches on a matrix goes like this:
```py
def traverse(matrix):
rows, cols = len(matrix), len(matrix[0])
visited = set()
directions = ((0, 1), (0, -1), (1, 0), (-1, 0))
def dfs(i, j):
if (i, j) in visited:
return
visited.add((i, j))
# Traverse neighbors
for direction in directions:
next_i, next_j = i + direction[0], j + direction[1]
if 0 <= next_i < rows and 0 <= next_j < cols: # Check boundary
# Add any other checking here ^
dfs(next_i, next_j)
for i in range(rows):
for j in range(cols):
dfs(i, j)
```
#### Corner Cases
- Empty graph.
- Graph with one or two nodes.
- Disjoint graphs.
- Graph with cycles.
#### Practice Questions
- [Clone Graph](https://leetcode.com/problems/clone-graph/)
- [Course Schedule](https://leetcode.com/problems/course-schedule/)
- [Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow/)
- [Number of Islands](https://leetcode.com/problems/number-of-islands/)
- [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/)
- [Alien Dictionary (Leetcode Premium)](https://leetcode.com/problems/alien-dictionary/)
- [Graph Valid Tree (Leetcode Premium)](https://leetcode.com/problems/graph-valid-tree/)
- [Number of Connected Components in an Undirected Graph (Leetcode Premium)](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/)
## Interval
#### Notes
Interval questions are questions where you are given an array of two-element arrays (an interval) and the two values represent a start and an end value. Interval questions are considered part of the array family but they involve some common techniques hence they are extracted out to this special section of their own.
An example interval array: `[[1, 2], [4, 7]]`.
Interval questions can be tricky to those who have not tried them before because of the sheer number of cases to consider when they overlap.
Do clarify with the interviewer whether `[1, 2]` and `[2, 3]` are considered overlapping intervals as it affects how you will write your equality checks.
A common routine for interval questions is to sort the array of intervals by each interval's starting value.
Be familiar with writing code to check if two intervals overlap and merging two overlapping intervals:
```py
def is_overlap(a, b):
return a[0] < b[1] and b[0] < a[1]
def merge_overlapping_intervals(a, b):
return [min(a[0], b[0]), max(a[1], b[1])]
```
#### Corner Cases
- Single interval.
- Non-overlapping intervals.
- An interval totally consumed within another interval.
- Duplicate intervals.
#### Practice Questions
- [Insert Interval](https://leetcode.com/problems/insert-interval/)
- [Merge Intervals](https://leetcode.com/problems/merge-intervals/)
- [Non-overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/)
- [Meeting Rooms (Leetcode Premium)](https://leetcode.com/problems/meeting-rooms/) and [Meeting Rooms II (Leetcode Premium)](https://leetcode.com/problems/meeting-rooms-ii/)
## Linked List
#### Notes
Like arrays, linked lists are used to represent sequential data. The benefit of linked lists is that insertion and deletion from anywhere in the list is O(1) whereas in arrays the following elements will have to be shifted.
Adding a dummy node at the head and/or tail might help to handle many edge cases where operations have to be performed at the head or the tail. The presence of dummy nodes essentially ensures that operations will never have be done on the head or the tail, thereby removing a lot of headache in writing conditional checks to dealing with null pointers. Be sure to remember to remove them at the end of the operation.
Sometimes linked lists problem can be solved without additional storage. Try to borrow ideas from reverse a linked list problem.
For deletion in linked lists, you can either modify the node values or change the node pointers. You might need to keep a reference to the previous element.
For partitioning linked lists, create two separate linked lists and join them back together.
Linked lists problems share similarity with array problems, think about how you would do it for an array and try to apply it to a linked list.
Two pointer approaches are also common for linked lists. For example:
- Getting the k<sup>th</sup> from last node - Have two pointers, where one is k nodes ahead of the other. When the node ahead reaches the end, the other node is k nodes behind.
- Detecting cycles - Have two pointers, where one pointer increments twice as much as the other, if the two pointers meet, means that there is a cycle.
- Getting the middle node - Have two pointers, where one pointer increments twice as much as the other. When the faster node reaches the end of the list, the slower node will be at the middle.
Be familiar with the following routines because many linked list questions make use of one or more of these routines in the solution:
- Counting the number of nodes in the linked list.
- Reversing a linked list in-place.
- Finding the middle node of the linked list using fast/slow pointers.
- Merging two lists together.
#### Corner Cases
- Single node.
- Two nodes.
- Linked list has cycle. Clarify with the interviewer whether there can be a cycle in the list. Usually the answer is no.
#### Practice Questions
- [Reverse a Linked List](https://leetcode.com/problems/reverse-linked-list/)
- [Detect Cycle in a Linked List](https://leetcode.com/problems/linked-list-cycle/)
- [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)
- [Merge K Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/)
- [Remove Nth Node From End Of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)
- [Reorder List](https://leetcode.com/problems/reorder-list/)
## Math
#### Notes
If code involves division or modulo, remember to check for division or modulo by 0 case.
When a question involves "a multiple of a number", perhaps modulo might be useful.
Check for and handle overflow/underflow if you are using a typed language like Java and C++. At the very least, mention that overflow/underflow is possible and ask whether you need to handle it.
Consider negative numbers and floating point numbers. This may sound obvious, but under interview pressure, many obvious cases go unnoticed.
If the question asks to implement an operator such as power, squareroot or division and want it to be faster than O(n), binary search is usually the approach to go.
#### Some common formulas:
- Sum of 1 to N = (n+1) * n/2
- Sum of GP = 2<sup>0</sup> + 2<sup>1</sup> + 2<sup>2</sup> + 2<sup>3</sup> + ... 2<sup>n</sup> = 2<sup>n+1</sup> - 1
- Permutations of N = N! / (N-K)!
- Combinations of N = N! / (K! * (N-K)!)
#### Practice Questions
- [Pow(x, n)](https://leetcode.com/problems/powx-n/)
- [Sqrt(x)](https://leetcode.com/problems/sqrtx/)
- [Integer to English Words](https://leetcode.com/problems/integer-to-english-words/)
## Matrix
#### Notes
A matrix is a 2-dimensional array. Questions involving matrices are usually related to dynamic programming or graph traversal.
For questions involving traversal or dynamic programming, you almost always want to make a copy of the matrix with the same dimensions that is initialized to empty values to store the visited state or dynamic programming table. Be familiar with such a routine:
```py
rows, cols = len(matrix), len(matrix[0])
copy = [[0 for _ in range(cols)] for _ in range(rows)]
```
Many grid-based games can be modeled as a matrix, such as Tic-Tac-Toe, Sudoku, Crossword, Connect 4, Battleship, etc. It is not uncommon to be asked to verify the winning condition of the game. For games like Tic-Tac-Toe, Connect 4 and Crosswords, where verification has to be done vertically and horizontally, one trick is to write code to verify the matrix for the horizontal cells, transpose the matrix and reuse the logic for horizontal verification to verify originally vertical cells (which are now horizontal).
Transposing a matrix in Python is simply:
```py
transposed_matrix = zip(*matrix)
```
#### Corner Cases
- Empty matrix. Check that none of the arrays are 0 length.
- 1 x 1 matrix.
- Matrix with only one row or column.
#### Practice Questions
- [Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/)
- [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/)
- [Rotate Image](https://leetcode.com/problems/rotate-image/)
- [Word Search](https://leetcode.com/problems/word-search/)
## Recursion
#### Notes
Recursion is useful for permutation, because it generates all combinations and tree-based questions. You should know how to generate all permutations of a sequence as well as how to handle duplicates.
Remember to always define a base case so that your recursion will end.
Recursion implicitly uses a stack. Hence all recursive approaches can be rewritten iteratively using a stack. Beware of cases where the recursion level goes too deep and causes a stack overflow (the default limit in Python is 1000). You may get bonus points for pointing this out to the interviewer. Recursion will never be O(1) space complexity because a stack is involved, unless there is [tail-call optimization](https://stackoverflow.com/questions/310974/what-is-tail-call-optimization) (TCO). Find out if your chosen language supports TCO.
#### Practice Questions
- [Subsets](https://leetcode.com/problems/subsets/) and [Subsets II](https://leetcode.com/problems/subsets-ii/)
- [Strobogrammatic Number II (Leetcode Premium)](https://leetcode.com/problems/strobogrammatic-number-ii/)
## String
#### Notes
Please read the above tips on sequence. They apply to strings too.
Ask about input character set and case sensitivity. Usually the characters are limited to lowercase Latin characters, for example a to z.
When you need to compare strings where the order isnt important (like anagram), you may consider using a HashMap as a counter. If your language has a built-in Counter class like Python, ask to use that instead.
If you need to keep a counter of characters, a common mistake is to say that the space complexity required for the counter is O(n). The space required for a counter is O(1) not O(n). This is because the upper bound is the range of characters, which is usually a fixed constant of 26. The input set is just lowercase Latin characters.
Common data structures for looking up strings efficiently are
- [Trie / Prefix Tree](https://en.wikipedia.org/wiki/Trie)
- [Suffix Tree](https://en.wikipedia.org/wiki/Suffix_tree)
Common string algorithms are
- [Rabin Karp](https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm) for efficient searching of substring using a rolling hash.
- [KMP](https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm) for efficient searching of substring.
#### Corner Cases
- Strings with only one distinct character.
#### Non-repeating Characters
- Use a 26-bit bitmask to indicate which lower case latin characters are inside the string.
```py
mask = 0
for c in set(word):
mask |= (1 << (ord(c) - ord('a')))
```
To determine if two strings have common characters, perform & on the two bitmasks. If the result is non-zero, `mask_a & mask_b > 0`, then the two strings have common characters.
### Anagram
An anagram is word switch or word play. It is the result of re-arranging the letters of a word or phrase to produce a new word or phrase, while using all the original letters only once. In interviews, usually we are only bothered with words without spaces in them.
To determine if two strings are anagrams, there are a few plausible approaches:
- Sorting both strings should produce the same resulting string. This takes O(nlgn) time and O(lgn) space.
- If we map each character to a prime number and we multiply each mapped number together, anagrams should have the same multiple (prime factor decomposition). This takes O(n) time and O(1) space.
- Frequency counting of characters will help to determine if two strings are anagrams. This also takes O(n) time and O(1) space.
### Palindrome
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward, such as *madam* or *racecar*.
Here are ways to determine if a string is a palindrome:
- Reverse the string and it should be equal to itself.
- Have two pointers at the start and end of the string. Move the pointers inward till they meet. At any point in time, the characters at both pointers should match.
The order of characters within the string matters, so HashMaps are usually not helpful.
When a question is about counting the number of palindromes, a common trick is to have two pointers that move outward, away from the middle. Note that palindromes can be even or odd length. For each middle pivot position, you need to check it twice: Once that includes the character and once without the character.
- For substrings, you can terminate early once there is no match.
- For subsequences, use dynamic programming as there are overlapping subproblems. Check out [this question](https://leetcode.com/problems/longest-palindromic-subsequence/).
#### Practice Questions
- [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/)
- [Longest Repeating Character Replacement](https://leetcode.com/problems/longest-repeating-character-replacement/)
- [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/description/)
- [Valid Anagram](https://leetcode.com/problems/valid-anagram)
- [Group Anagrams](https://leetcode.com/problems/group-anagrams/)
- [Valid Parentheses](https://leetcode.com/problems/valid-parentheses)
- [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/)
- [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/)
- [Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/)
- [Encode and Decode Strings (Leetcode Premium)](https://leetcode.com/problems/encode-and-decode-strings/)
## Tree
#### Study Links
- [Leaf It Up To Binary Trees](https://medium.com/basecs/leaf-it-up-to-binary-trees-11001aaf746d)
#### Notes
A tree is an undirected and connected acyclic graph.
Recursion is a common approach for trees. When you notice that the subtree problem can be used to solve the entire problem, try using recursion.
When using recursion, always remember to check for the base case, usually where the node is `null`.
When you are asked to traverse a tree by level, use depth first search.
Sometimes it is possible that your recursive function needs to return two values.
If the question involves summation of nodes along the way, be sure to check whether nodes can be negative.
You should be very familiar with writing pre-order, in-order, and post-order traversal recursively. As an extension, challenge yourself by writing them iteratively. Sometimes interviewers ask candidates for the iterative approach, especially if the candidate finishes writing the recursive approach too quickly.
#### Corner Cases
- Empty tree.
- Single node.
- Two nodes.
- Very skewed tree (like a linked list).
### Binary Tree
In-order traversal of a binary tree is insufficient to uniquely serialize a tree. Pre-order or post-order traversal is also required.
### Binary Search Tree (BST)
In-order traversal of a BST will give you all elements in order.
Be very familiar with the properties of a BST and validating that a binary tree is a BST. This comes up more often than expected.
When a question involves a BST, the interviewer is usually looking for a solution which runs faster than O(n).
#### Practice Questions
- [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/)
- [Same Tree](https://leetcode.com/problems/same-tree/)
- [Invert/Flip Binary Tree](https://leetcode.com/problems/invert-binary-tree/)
- [Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/)
- [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/)
- [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/)
- [Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/)
- [Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/)
- [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)
- [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/)
- [Lowest Common Ancestor of BST](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/)
## Trie
#### Study Links
- [Trying to Understand Tries](https://medium.com/basecs/trying-to-understand-tries-3ec6bede0014)
- [Implement Trie (Prefix Tree)](https://leetcode.com/articles/implement-trie-prefix-tree/)
#### Notes
Tries are special trees (prefix trees) that make searching and storing strings more efficient. Tries have many practical applications, such as conducting searches and providing autocomplete. It is helpful to know these common applications so that you can easily identify when a problem can be efficiently solved using a trie.
Sometimes preprocessing a dictionary of words (given in a list) into a trie, will improve the efficiency of searching for a word of length k, among n words. Searching becomes O(k) instead of O(n).
Be familiar with implementing, from scratch, a `Trie` class and its `add`, `remove` and `search` methods.
#### Practice Questions
- [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree)
- [Add and Search Word](https://leetcode.com/problems/add-and-search-word-data-structure-design)
- [Word Search II](https://leetcode.com/problems/word-search-ii/)
## Heap
#### Study Links
- [Learning to Love Heaps](https://medium.com/basecs/learning-to-love-heaps-cef2b273a238)
#### Notes
If you see a top or lowest *k* being mentioned in the question, it is usually a signal that a heap can be used to solve the problem, such as in [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/).
If you require the top *k* elements use a Min Heap of size *k*. Iterate through each element, pushing it into the heap. Whenever the heap size exceeds *k*, remove the minimum element, that will guarantee that you have the *k* largest elements.
#### Practice Questions
- [Merge K Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/)
- [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/)
- [Find Median from Data Stream](https://leetcode.com/problems/find-median-from-data-stream/)
###### References
- http://blog.triplebyte.com/how-to-pass-a-programming-interview
- https://quip.com/q41AA3OmoZbC
- http://www.geeksforgeeks.org/must-do-coding-questions-for-companies-like-amazon-microsoft-adobe/
- https://medium.com/basecs
<!-- TODO: Remove in future -->

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

@ -1,7 +0,0 @@
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.

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

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

@ -1,10 +0,0 @@
Graph
==
- Given a list of sorted words from an alien dictionary, find the order of the alphabet.
- Alien Dictionary Topological Sort question.
- Find if a given string matches any path in a labeled graph. A path may contain cycles.
- Given a bipartite graph, separate the vertices into two sets.
- You are a thief trying to sneak across a rectangular 100 x 100m field. There are alarms placed on the fields and they each have a circular sensing radius which will trigger if anyone steps into it. Each alarm has its own radius. Determine if you can get from one end of the field to the other end.
- Given a graph and two nodes, determine if there exists a path between them.
- Determine if a cycle exists in the graph.

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

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

@ -1,12 +0,0 @@
Linked List
==
- Given a linked list, in addition to the next pointer, each node has a child pointer that can point to a separate list. With the head node, flatten the list to a single-level linked list.
- [Source](http://blog.gainlo.co/index.php/2016/06/12/flatten-a-linked-list/)
- Reverse a singly linked list. Implement it recursively and iteratively.
- Convert a binary tree to a doubly circular linked list.
- Implement an LRU cache with O(1) runtime for all its operations.
- Check distance between values in linked list.
- A question involving an API's integration with hash map where the buckets of hash map are made up of linked lists.
- Given a singly linked list (a list which can only be traversed in one direction), find the item that is located at 'k' items from the end. So if the list is a, b, c, d and k is 2 then the answer is 'c'. The solution should not search the list twice.
- How can you tell if a Linked List is a Palindrome?

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

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

@ -1,58 +0,0 @@
String
==
- Output list of strings representing a page of hostings given a list of CSV strings.
- Given a list of words, find the word pairs that when concatenated form a palindrome.
- Find the most efficient way to identify what character is out of place in a non-palindrome.
- Implement a simple regex parser which, given a string and a pattern, returns a boolean indicating whether the input matches the pattern. By simple, we mean that the regex can only contain the following special characters: `*` (star), `.` (dot), `+` (plus). The star means that there will be zero or more of the previous character in that place in the pattern. The dot means any character for that position. The plus means one or more of previous character in that place in the pattern.
- Find all words from a dictionary that are x edit distance away.
- Given a string IP and number n, print all CIDR addresses that cover that range.
- Write a function called `eval`, which takes a string and returns a boolean. This string is allowed 6 different characters: `0`, `1`, `&`, `|`, `(`, and `)`. `eval` should evaluate the string as a boolean expression, where `0` is `false`, `1` is `true`, `&` is an `and`, and `|` is an `or`.
- E.g `"(0 | (1 | 0)) & (1 & ((1 | 0) & 0))"`
- Given a pattern string like `"abba"` and an input string like `"redbluebluered"`, return `true` if and only if there's a one to one mapping of letters in the pattern to substrings of the input.
- E.g. `"abba"` and `"redbluebluered"` should return `true`.
- E.g. `"aaaa"` and `"asdasdasdasd"` should return `true`.
- E.g. `"aabb"` and `"xyzabcxzyabc"` should return `false`.
- If you received a file in chunks, calculate when you have the full file. Quite an open-ended question. Can assume chunks come with start and end, or size, etc.
- Given a list of names (strings) and the width of a line, design an algorithm to display them using the minimum number of lines.
- Design a spell-checking algorithm.
- Count and say problem.
- Longest substring with `K` unique characters.
- [Source](http://blog.gainlo.co/index.php/2016/04/12/find-the-longest-substring-with-k-unique-characters/)
- Given a set of random strings, write a function that returns a set that groups all the anagrams together.
- [Source](http://blog.gainlo.co/index.php/2016/05/06/group-anagrams/)
- Given a string, find the longest substring without repeating characters. For example, for string `'abccdefgh'`, the longest substring is `'cdefgh'`.
- [Source](http://blog.gainlo.co/index.php/2016/10/07/facebook-interview-longest-substring-without-repeating-characters/)
- Given a string, return the string with duplicate characters removed.
- Write a function that receives a regular expression (allowed chars = from `'a'` to `'z'`, `'*'`, `'.'`) and a string containing lower case english alphabet characters and return `true` or `false` whether the string matches the regex.
- E.g. `'ab*a'`, `'abbbbba'` => `true`.
- E.g. `'ab*b.'`, `'aba'` => `true`.
- E.g. `'abc*'`, `'acccc'` => `false`.
- Given a rectangular grid with letters, search if some word is in the grid.
- Given two strings representing integer numbers (`'123'` , `'30'`) return a string representing the sum of the two numbers: `'153'`.
- A professor wants to see if two students have cheated when writing a paper. Design a function `hasCheated(String s1, String s2, int N)` that evaluates to `true` if two strings have a common substring of length `N`.
- Follow up: Assume you don't have the possibility of using `String.contains()` and `String.substring()`. How would you implement this?
- Print all permutations of a given string.
- Parse a string containing numbers and `'+'`, `'-'` and parentheses. Evaluate the expression. `-2+(3-5)` should return `-4`.
- Output a substring with at most `K` unique characters.
- E.g. `'aabc'` and `k` = 2 => `'aab'`.
- Ensure that there are a minimum of `N` dashes between any two of the same characters of a string.
- E.g. `n = 2, string = 'ab-bcdecca'` => `'ab--bcdec--ca'`.
- Find the longest palindrome in a string.
- Give the count and the number following in the series.
- E.g. `1122344`, next: `21221324`, next: `12112211121214`.
- Count and say problem.
- Compress a string by grouping consecutive similar questions together:
- E.g. `'aaabbbcc' => `'a3b3c2'`.
- You have a string consisting of open and closed parentheses, but parentheses may be imbalanced. Make the parentheses balanced and return the new string.
- Given a set of strings, return the smallest subset that contains prefixes for every string.
- E.g. `['foo', 'foog', 'food', 'asdf']` => `['foo', 'asdf']`.
- Write a function that would return all the possible words generated when using a phone (pre-smartphone era) numpad to type.
- Given a dictionary and a word, find the minimum number of deletions needed on the word in order to make it a valid word.
- [Source](http://blog.gainlo.co/index.php/2016/04/29/minimum-number-of-deletions-of-a-string/)
- How to check if a string contains an anagram of another string?
- [Source](http://blog.gainlo.co/index.php/2016/04/08/if-a-string-contains-an-anagram-of-another-string/)
- Find all k-lettered words from a string.
- Given a string of open and close parentheses, find the minimum number of edits needed to balance a string of parentheses.
- Run length encoding - Write a string compress function that returns `'R2G1B1'` given `'RRGB'`.
- Write a function that finds all the different ways you can split up a word into a concatenation of two other words.

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

@ -1,43 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 582.39 458.49">
<defs>
<style>
.cls-1{fill:#eef2f5;}.cls-2{fill:#5252ee;}.cls-3{fill:#7f7ff0;}.cls-4{fill:#fff;}.cls-5{fill:#ffcb2c;}.cls-6{opacity:0.2;}.cls-7{fill:#363636;}.cls-8{opacity:0.1;}.cls-9{fill:#ffe400;}.cls-10{fill:#ff4585;}.cls-11{fill:#00e5a0;}
</style>
</defs>
<g id="Layer_2" data-name="Layer 2">
<g id="Layer_1-2" data-name="Layer 1">
<ellipse class="cls-1" cx="291.19" cy="428.46" rx="291.19" ry="30.03"/>
<rect class="cls-2" x="197.89" y="168.35" width="346.05" height="180.28" rx="30" ry="30" transform="rotate(-90 370.92 258.49)"/>
<rect class="cls-3" x="189.19" y="168.35" width="346.05" height="180.28" rx="30" ry="30" transform="rotate(-90 362.22 258.49)"/>
<path class="cls-4" d="M257.71 419.94V97.04h152.1a28.18 28.18 0 0 1 28.18 28.18v266.54a28.18 28.18 0 0 1-28.18 28.18h-152.1z"/>
<path class="cls-2" d="M206.96 431.51v-346h151.11a29.17 29.17 0 0 1 29.17 29.08v287.75a29.17 29.17 0 0 1-29.17 29.17H206.96z"/>
<rect class="cls-3" x="80.86" y="136.46" width="346.05" height="244.06" rx="33.94" ry="33.94" transform="rotate(-90 253.89 258.49)"/>
<path class="cls-5" d="M131.87 397.57V119.41a33.94 33.94 0 0 1 33.94-33.94h5.06v346h-5.07a33.94 33.94 0 0 1-33.93-33.9z"/>
<g class="cls-6">
<circle cx="148.62" cy="375.73" r="11.84"/>
<circle cx="148.62" cy="329.54" r="11.84"/>
<circle cx="148.62" cy="283.35" r="11.84"/>
<circle cx="148.62" cy="237.16" r="11.84"/>
<circle cx="148.62" cy="190.96" r="11.84"/>
<circle cx="148.62" cy="144.77" r="11.84"/>
</g>
<rect class="cls-7" x="129.79" y="362.01" width="11.93" height="27.44" rx="4.5" ry="4.5" transform="rotate(-90 135.755 375.735)"/>
<rect class="cls-7" x="129.79" y="315.82" width="11.93" height="27.44" rx="4.5" ry="4.5" transform="rotate(-90 135.75 329.54)"/>
<rect class="cls-7" x="129.79" y="269.63" width="11.93" height="27.44" rx="4.5" ry="4.5" transform="rotate(-90 135.75 283.35)"/>
<rect class="cls-7" x="129.79" y="223.44" width="11.93" height="27.44" rx="4.5" ry="4.5" transform="rotate(-90 135.75 237.16)"/>
<rect class="cls-7" x="129.79" y="177.24" width="11.93" height="27.44" rx="4.5" ry="4.5" transform="rotate(-90 135.755 190.965)"/>
<rect class="cls-7" x="129.79" y="131.05" width="11.93" height="27.44" rx="4.5" ry="4.5" transform="rotate(-90 135.75 144.77)"/>
<path class="cls-8" d="M396.07 97.04h2.47v189.3h-2.47zM396.07 330.16h2.47v90.57h-2.47zM411.51 222.19h2.47v197.75h-2.47zM427.57 232.87h-2.47V101.54l2.47 1.79v129.54zM425.1 291.58h2.47v45.59h-2.47zM411.51 128.58h2.47v45.59h-2.47z"/>
<path class="cls-4" d="M237.95 271a5 5 0 0 1-3.54-1.46L211.9 247a5 5 0 0 1 0-7.07l22.51-22.51a5 5 0 0 1 7.07 7.07l-19 19 19 19a5 5 0 0 1-3.54 8.54zM302.77 271a5 5 0 0 1-3.54-8.54l19-19-19-19a5 5 0 0 1 7.07-7.07l22.51 22.51a5 5 0 0 1 0 7.07l-22.51 22.51a5 5 0 0 1-3.53 1.52zM261.19 285.87a5 5 0 0 1-4.84-6.27l19.72-74.85a5 5 0 1 1 9.67 2.55L266 282.14a5 5 0 0 1-4.81 3.73z"/>
<path class="cls-9" d="M92.72 186.5l5 13.1A2.32 2.32 0 0 0 99 201l13.1 5a2.32 2.32 0 0 1 0 4.34l-13.1 5a2.32 2.32 0 0 0-1.35 1.35l-5 13.1a2.32 2.32 0 0 1-4.34 0l-5-13.1a2.32 2.32 0 0 0-1.35-1.35l-13.1-5a2.32 2.32 0 0 1 0-4.34l13.1-5a2.32 2.32 0 0 0 1.35-1.35l5-13.1a2.32 2.32 0 0 1 4.41-.05zM479.08 265.89l5.38 14.22a2.52 2.52 0 0 0 1.47 1.47l14.22 5.42a2.52 2.52 0 0 1 0 4.72l-14.22 5.38a2.52 2.52 0 0 0-1.47 1.47l-5.38 14.22a2.52 2.52 0 0 1-4.72 0L469 298.52a2.52 2.52 0 0 0-1.47-1.47l-14.22-5.38a2.52 2.52 0 0 1 0-4.72l14.22-5.38a2.52 2.52 0 0 0 1.47-1.47l5.38-14.22a2.52 2.52 0 0 1 4.7.01zM258.14 18l5.67 15a2.66 2.66 0 0 0 1.55 1.55l15 5.67a2.66 2.66 0 0 1 0 5l-15 5.67a2.66 2.66 0 0 0-1.55 1.55l-5.67 15a2.66 2.66 0 0 1-5 0l-5.67-15a2.66 2.66 0 0 0-1.55-1.55l-15-5.67a2.66 2.66 0 0 1 0-5l15-5.67a2.66 2.66 0 0 0 1.55-1.55l5.67-15a2.66 2.66 0 0 1 5 0zM208.45 362.87l5.67 15a2.66 2.66 0 0 0 1.55 1.55l15 5.67a2.66 2.66 0 0 1 0 5l-15 5.67a2.66 2.66 0 0 0-1.55 1.55l-5.67 15a2.66 2.66 0 0 1-5 0l-5.67-15a2.66 2.66 0 0 0-1.55-1.55l-15-5.67a2.66 2.66 0 0 1 0-5l15-5.67a2.66 2.66 0 0 0 1.55-1.55l5.67-15a2.66 2.66 0 0 1 5 0z"/>
<rect class="cls-10" x="480.14" y="173.05" width="90.16" height="59.5" rx="11.44" ry="11.44" transform="rotate(30.42 525.27 202.83)"/>
<path class="cls-10" d="M505.53 242.61a4.27 4.27 0 0 1-5.83-3.43l-1.49-11.87-1.1-8.77a4.27 4.27 0 0 1 6.4-4.21l10.94 6.42 10.94 6.42a4.27 4.27 0 0 1-.56 7.64l-8.19 3.31z"/>
<circle class="cls-4" cx="507.01" cy="194.63" r="5.78" transform="rotate(-59.76 507.024 194.63)"/>
<circle class="cls-4" cx="524.1" cy="204.6" r="5.78" transform="rotate(-59.76 524.112 204.598)"/>
<circle class="cls-4" cx="541.31" cy="214.63" r="5.78" transform="rotate(-59.76 541.326 214.627)"/>
<rect class="cls-11" x="69.02" y="11.6" width="86.2" height="56.89" rx="10.94" ry="10.94" transform="rotate(-24.07 112.12 40.037)"/>
<path class="cls-11" d="M132.16 77.47a4.08 4.08 0 0 1-5.9 2.64l-10.06-5.43-7.43-4a4.08 4.08 0 0 1 .27-7.32l11.07-4.95 11.07-4.95a4.08 4.08 0 0 1 5.63 4.68l-2 8.21z"/>
<path class="cls-4" d="M115.94 53.34l-17.08-5.28 2.41-7.83 9.67 2.99 7.81-21.18 7.68 2.84-10.49 28.46z"/>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 5.2 KiB

@ -0,0 +1,49 @@
---
id: array
title: Array
---
## Notes
Is the array sorted or partially sorted? If it is, some form of binary search should be possible. This also usually means that the interviewer is looking for a solution that is faster than O(n).
Can you sort the array? Sometimes sorting the array first may significantly simplify the problem. Make sure that the order of array elements do not need to be preserved before attempting a sort.
For questions where summation or multiplication of a subarray is involved, pre-computation using hashing or a prefix/suffix sum/product might be useful.
If you are given a sequence and the interviewer asks for O(1) space, it might be possible to use the array itself as a hash table. For example, if the array only has values from 1 to N, where N is the length of the array, negate the value at that index (minus one) to indicate presence of that number.
Also O(n) doesn't mean you can only traverse the array once. Sometimes traversing the array more than once can help you solve the problem easily.
## Arrays are sequences
Are there duplicate values in the array, would it affect the answer?
When using an index to iterate through array elements, be careful not to go out of bounds.
Be mindful about slicing or concatenating arrays in your code. Typically, slicing and concatenating arrays require O(n) time. Use start and end indices to demarcate a subarray/range where possible.
Sometimes you can traverse the array from the right rather than from the left.
Master the [sliding window technique](https://discuss.leetcode.com/topic/30941/here-is-a-10-line-template-that-can-solve-most-substring-problems) that applies to many subarray problems.
When you are given two arrays to process, it is common to have one index per array (pointer) to traverse/compare the both of them. For example, we use the same approach to merge two sorted arrays.
## Corner cases
- Empty sequence
- Sequence with 1 or 2 elements
- Sequence with repeated elements
## Recommended LeetCode questions
- [Two Sum](https://leetcode.com/problems/two-sum/)
- [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)
- [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/)
- [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/)
- [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/)
- [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/)
- [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/)
- [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/)
- [3Sum](https://leetcode.com/problems/3sum/)
- [Container With Most Water](https://leetcode.com/problems/container-with-most-water/)

@ -0,0 +1,33 @@
---
id: binary
title: Binary
---
## Study links
- [Bits, Bytes, Building With Binary](https://medium.com/basecs/bits-bytes-building-with-binary-13cb4289aafa)
## Notes
Questions involving binary representations and bitwise operations are asked sometimes and you must be absolutely familiar with how to convert a number from decimal form into binary form (and vice versa) in your chosen programming language.
Some helpful utility snippets:
- Test k<sup>th</sup> bit is set: `num & (1 << k) != 0`.
- Set k<sup>th</sup> bit: `num |= (1 << k)`.
- Turn off k<sup>th</sup> bit: `num &= ~(1 << k)`.
- Toggle the k<sup>th</sup> bit: `num ^= (1 << k)`.
- To check if a number is a power of 2, `num & num - 1 == 0`.
## Corner cases
- Be aware and check for overflow/underflow
- Negative numbers
## Recommended LeetCode questions
- [Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers/)
- [Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits/)
- [Counting Bits](https://leetcode.com/problems/counting-bits/)
- [Missing Number](https://leetcode.com/problems/missing-number/)
- [Reverse Bits](https://leetcode.com/problems/reverse-bits/)

@ -0,0 +1,29 @@
---
id: dynamic-programming
title: Dynamic Programming
---
## Study links
- [Demystifying Dynamic Programming](https://medium.freecodecamp.org/demystifying-dynamic-programming-3efafb8d4296)
- [Dynamic Programming 7 Steps to Solve any DP Interview Problem](https://dev.to/nikolaotasevic/dynamic-programming--7-steps-to-solve-any-dp-interview-problem-3870)
## Notes
Dynamic Programming (DP) is usually used to solve optimization problems. The only way to get better at DP is to practice. It takes some amount of practice to be able to recognize that a problem can be solved by DP.
Sometimes you do not need to store the whole DP table in memory, the last two values or the last two rows of the matrix will suffice.
## Recommended LeetCode questions
- 0/1 Knapsack
- [Climbing Stairs](https://leetcode.com/problems/climbing-stairs/)
- [Coin Change](https://leetcode.com/problems/coin-change/)
- [Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/)
- [Longest Common Subsequence](https://leetcode.com/problems/longest-common-subsequence/)
- [Word Break Problem](https://leetcode.com/problems/word-break/)
- [Combination Sum](https://leetcode.com/problems/combination-sum-iv/)
- [House Robber](https://leetcode.com/problems/house-robber/) and [House Robber II](https://leetcode.com/problems/house-robber-ii/)
- [Decode Ways](https://leetcode.com/problems/decode-ways/)
- [Unique Paths](https://leetcode.com/problems/unique-paths/)
- [Jump Game](https://leetcode.com/problems/jump-game/)

@ -0,0 +1,17 @@
---
id: geometry
title: Geometry
---
## Notes
When comparing euclidean distance between two pairs of points, using dx<sup>2</sup> + dy<sup>2</sup> is sufficient. It is unnecessary to square root the value.
To find out if two circles overlap, check that the distance between the two centers of the circles is less than the sum of their radii.
## Sample questions
- You have a plane with lots of rectangles on it, find out how many of them intersect.
- Which data structure would you use to query the k-nearest points of a set on a 2D plane?
- Given many points, find k points that are closest to the origin.
- How would you triangulate a polygon?

@ -0,0 +1,113 @@
---
id: graph
title: Graph
---
## Study links
- [From Theory To Practice: Representing Graphs](https://medium.com/basecs/from-theory-to-practice-representing-graphs-cfd782c5be38)
- [Deep Dive Through A Graph: DFS Traversal](https://medium.com/basecs/deep-dive-through-a-graph-dfs-traversal-8177df5d0f13)
- [Going Broad In A Graph: BFS Traversal](https://medium.com/basecs/going-broad-in-a-graph-bfs-traversal-959bd1a09255)
## Notes
Be familiar with the various graph representations, graph search algorithms and their time and space complexities.
You can be given a list of edges and tasked to build your own graph from the edges to perform a traversal on. The common graph representations are:
- Adjacency matrix.
- Adjacency list.
- Hashmap of hashmaps.
A tree-like diagram could very well be a graph that allows for cycles and a naive recursive solution would not work. In that case you will have to handle cycles and keep a set of visited nodes when traversing.
## Graph search algorithms:
- **Common** - Breadth-first Search, Depth-first Search
- **Uncommon** - Topological Sort, Dijkstra's algorithm
- **Rare** - Bellman-Ford algorithm, Floyd-Warshall algorithm, Prim's algorithm, Kruskal's algorithm
In coding interviews, graphs are commonly represented as 2-D matrices where cells are the nodes and each cell can traverse to its adjacent cells (up/down/left/right). Hence it is important that you be familiar with traversing a 2-D matrix. When traversing the matrix, always ensure that your current position is within the boundary of the matrix and has not been visited before.
A simple template for doing depth-first searches on a matrix goes like this:
```py
def dfs(matrix):
# Check for an empty graph.
if not matrix:
return []
rows, cols = len(matrix), len(matrix[0])
visited = set()
directions = ((0, 1), (0, -1), (1, 0), (-1, 0))
def traverse(i, j):
if (i, j) in visited:
return
visited.add((i, j))
# Traverse neighbors.
for direction in directions:
next_i, next_j = i + direction[0], j + direction[1]
if 0 <= next_i < rows and 0 <= next_j < cols:
# Add in your question-specific checks.
traverse(next_i, next_j)
for i in range(rows):
for j in range(cols):
traverse(i, j)
```
A similar template for doing breadth-first searches on the matrix goes like this:
```py
from collections import deque
def bfs(matrix):
# Check for an empty graph.
if not matrix:
return []
rows, cols = len(matrix), len(matrix[0])
visited = set()
directions = ((0, 1), (0, -1), (1, 0), (-1, 0))
def traverse(i, j):
queue = deque([(i, j)])
while queue:
curr_i, curr_j = queue.popleft()
if (curr_i, curr_j) not in visited:
visited.add((curr_i, curr_j))
# Traverse neighbors.
for direction in directions:
next_i, next_j = curr_i + direction[0], curr_j + direction[1]
if 0 <= next_i < rows and 0 <= next_j < cols:
# Add in your question-specific checks.
queue.append((next_i, next_j))
for i in range(rows):
for j in range(cols):
traverse(i, j)
```
> NOTE: While DFS is implemented using recursion in this sample, it could also be implemented iteratively similar to BFS. The key difference between the algorithms lies in the underlying data structure (BFS uses a queue while DFS uses a stack). The `deque` class in Python can function as both a stack and a queue
For additional tips on BFS and DFS, you can refer to this [LeetCode post](https://leetcode.com/problems/pacific-atlantic-water-flow/discuss/90774/Python-solution-with-detailed-explanation)
## Corner cases
- Empty graph
- Graph with one or two nodes
- Disjoint graphs
- Graph with cycles
## Recommended LeetCode questions
- [Clone Graph](https://leetcode.com/problems/clone-graph/)
- [Course Schedule](https://leetcode.com/problems/course-schedule/)
- [Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow/)
- [Number of Islands](https://leetcode.com/problems/number-of-islands/)
- [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/)
- [Alien Dictionary (LeetCode Premium)](https://leetcode.com/problems/alien-dictionary/)
- [Graph Valid Tree (LeetCode Premium)](https://leetcode.com/problems/graph-valid-tree/)
- [Number of Connected Components in an Undirected Graph (LeetCode Premium)](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/)

@ -1,7 +1,10 @@
Hash Table
==
---
id: hash-table
title: Hash Table
---
## Sample questions
- Describe an implementation of a least-used cache, and big-O notation of it.
- A question involving an API's integration with hash map where the buckets of hash map are made up of linked lists.
- Implement data structure `Map` storing pairs of integers (key, value) and define following member functions in O(1) runtime: `void insert(key, value)`, `void delete(key)`, `int get(key)`, `int getRandomKey()`.
- [Source](http://blog.gainlo.co/index.php/2016/08/14/uber-interview-question-map-implementation/).
- Implement data structure `Map` storing pairs of integers (key, value) and define following member functions in O(1) runtime: `void insert(key, value)`, `void delete(key)`, `int get(key)`, `int getRandomKey()`. [(Solution)](http://blog.gainlo.co/index.php/2016/08/14/uber-interview-question-map-implementation/)

@ -0,0 +1,20 @@
---
id: heap
title: Heap
---
## Study links
- [Learning to Love Heaps](https://medium.com/basecs/learning-to-love-heaps-cef2b273a238)
## Notes
If you see a top or lowest _k_ being mentioned in the question, it is usually a signal that a heap can be used to solve the problem, such as in [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/).
If you require the top _k_ elements use a Min Heap of size _k_. Iterate through each element, pushing it into the heap. Whenever the heap size exceeds _k_, remove the minimum element, that will guarantee that you have the _k_ largest elements.
## Recommended LeetCode questions
- [Merge K Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/)
- [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/)
- [Find Median from Data Stream](https://leetcode.com/problems/find-median-from-data-stream/)

@ -0,0 +1,40 @@
---
id: interval
title: Interval
---
## Notes
Interval questions are questions where you are given an array of two-element arrays (an interval) and the two values represent a start and an end value. Interval questions are considered part of the array family but they involve some common techniques hence they are extracted out to this special section of their own.
An example interval array: `[[1, 2], [4, 7]]`.
Interval questions can be tricky to those who have not tried them before because of the sheer number of cases to consider when they overlap.
Do clarify with the interviewer whether `[1, 2]` and `[2, 3]` are considered overlapping intervals as it affects how you will write your equality checks.
A common routine for interval questions is to sort the array of intervals by each interval's starting value.
Be familiar with writing code to check if two intervals overlap and merging two overlapping intervals:
```py
def is_overlap(a, b):
return a[0] < b[1] and b[0] < a[1]
def merge_overlapping_intervals(a, b):
return [min(a[0], b[0]), max(a[1], b[1])]
```
## Corner cases
- Single interval
- Non-overlapping intervals
- An interval totally consumed within another interval
- Duplicate intervals
## Recommended LeetCode questions
- [Insert Interval](https://leetcode.com/problems/insert-interval/)
- [Merge Intervals](https://leetcode.com/problems/merge-intervals/)
- [Non-overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/)
- [Meeting Rooms (LeetCode Premium)](https://leetcode.com/problems/meeting-rooms/) and [Meeting Rooms II (LeetCode Premium)](https://leetcode.com/problems/meeting-rooms-ii/)

@ -0,0 +1,52 @@
---
id: algorithms-introduction
title: Introduction
---
This section dives deep into practical tips for specific topics of algorithms and data structures which appear frequently in coding questions. Many algorithm questions involve techniques that can be applied to questions of similar nature. The more techniques you have in your arsenal, the higher the chances of passing the interview. They may lead you to discover corner cases you might have missed out or even lead you towards the optimal approach!
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.
## 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?
Check for off-by-one errors.
In languages where there are no automatic type coercion, check that concatenation of values are of the same type: `int`/`str`/`list`.
After finishing your code, use a few example inputs to test your solution.
Is the algorithm meant to be run multiple times, for example in a web server? If yes, the input is likely to be preprocess-able to improve the efficiency in each call.
Use a mix of functional and imperative programming paradigms:
- Write pure functions as much as possible.
- Pure functions are easier to reason about and can help to reduce bugs in your implementation.
- Avoid mutating the parameters passed into your function especially if they are passed by reference unless you are sure of what you are doing.
- However, functional programming is usually expensive in terms of space complexity because of non-mutation and the repeated allocation of new objects. On the other hand, imperative code is faster because you operate on existing objects. Hence you will need to achieve a balance between accuracy vs efficiency, by using the right amount of functional and imperative code where appropriate.
- Avoid relying on and mutating global variables. Global variables introduce state.
- If you have to rely on global variables, make sure that you do not mutate it by accident.
Generally, to improve the speed of a program, we can either: (1) choose a more appropriate data structure/algorithm; or (2) use more memory. The latter demonstrates a classic space vs. time tradeoff, but it is not necessarily the case that you can only achieve better speed at the expense of space. Also, note that there is often a theoretical limit to how fast your program can run (in terms of time complexity). For instance, a question that requires you to find the smallest/largest element in an unsorted array cannot run faster than O(N).
Data structures are your weapons. Choosing the right weapon for the right battle is the key to victory. Be very familiar about the strengths of each data structure and the time complexities for its various operations.
Data structures can be augmented to achieve efficient time complexities across different operations. For example, a hash map can be used together with a doubly-linked list to achieve O(1) time complexity for both the `get` and `put` operation in an [LRU cache](https://leetcode.com/problems/lru-cache/).
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 common 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 may not cover all cases.
###### References
- http://blog.triplebyte.com/how-to-pass-a-programming-interview
- https://quip.com/q41AA3OmoZbC
- http://www.geeksforgeeks.org/must-do-coding-questions-for-companies-like-amazon-microsoft-adobe/
- https://medium.com/basecs

@ -0,0 +1,48 @@
---
id: linked-list
title: Linked List
---
## Notes
Like arrays, linked lists are used to represent sequential data. The benefit of linked lists is that insertion and deletion of a node in the list (given its location) is O(1) whereas in arrays the following elements will have to be shifted.
Adding a dummy node at the head and/or tail might help to handle many edge cases where operations have to be performed at the head or the tail. The presence of dummy nodes essentially ensures that operations will never have be done on the head or the tail, thereby removing a lot of headache in writing conditional checks to dealing with null pointers. Be sure to remember to remove them at the end of the operation.
Sometimes linked lists problem can be solved without additional storage. Try to borrow ideas from reverse a linked list problem.
For deletion in linked lists, you can either modify the node values or change the node pointers. You might need to keep a reference to the previous element.
For partitioning linked lists, create two separate linked lists and join them back together.
Linked lists problems share similarity with array problems, think about how you would do it for an array and try to apply it to a linked list.
Two pointer approaches are also common for linked lists. For example:
- Getting the k<sup>th</sup> from last node - Have two pointers, where one is k nodes ahead of the other. When the node ahead reaches the end, the other node is k nodes behind
- Detecting cycles - Have two pointers, where one pointer increments twice as much as the other, if the two pointers meet, means that there is a cycle
- Getting the middle node - Have two pointers, where one pointer increments twice as much as the other. When the faster node reaches the end of the list, the slower node will be at the middle
## Common Routines
Be familiar with the following routines because many linked list questions make use of one or more of these routines in the solution:
- Counting the number of nodes in the linked list
- Reversing a linked list in-place
- Finding the middle node of the linked list using fast/slow pointers
- Merging two lists together
## Corner cases
- Single node
- Two nodes
- Linked list has cycle. **Tip:** Clarify with the interviewer whether there can be a cycle in the list. Usually the answer is no
## Recommended LeetCode questions
- [Reverse a Linked List](https://leetcode.com/problems/reverse-linked-list/)
- [Detect Cycle in a Linked List](https://leetcode.com/problems/linked-list-cycle/)
- [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists/)
- [Merge K Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/)
- [Remove Nth Node From End Of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)
- [Reorder List](https://leetcode.com/problems/reorder-list/)

@ -0,0 +1,29 @@
---
id: math
title: Math
---
## Notes
If code involves division or modulo, remember to check for division or modulo by 0 case.
When a question involves "a multiple of a number", perhaps modulo might be useful.
Check for and handle overflow/underflow if you are using a typed language like Java and C++. At the very least, mention that overflow/underflow is possible and ask whether you need to handle it.
Consider negative numbers and floating point numbers. This may sound obvious, but under interview pressure, many obvious cases go unnoticed.
If the question asks to implement an operator such as power, squareroot or division and want it to be faster than O(n), binary search is usually the approach to go.
#### Some common formulas:
- Sum of 1 to N = (n+1) \* n/2
- Sum of GP = 2<sup>0</sup> + 2<sup>1</sup> + 2<sup>2</sup> + 2<sup>3</sup> + ... 2<sup>n</sup> = 2<sup>n+1</sup> - 1
- Permutations of N = N! / (N-K)!
- Combinations of N = N! / (K! \* (N-K)!)
## Recommended LeetCode questions
- [Pow(x, n)](https://leetcode.com/problems/powx-n/)
- [Sqrt(x)](https://leetcode.com/problems/sqrtx/)
- [Integer to English Words](https://leetcode.com/problems/integer-to-english-words/)

@ -0,0 +1,36 @@
---
id: matrix
title: Matrix
---
## Notes
A matrix is a 2-dimensional array. Questions involving matrices are usually related to dynamic programming or graph traversal.
For questions involving traversal or dynamic programming, you almost always want to make a copy of the matrix with the same dimensions that is initialized to empty values to store the visited state or dynamic programming table. Be familiar with such a routine:
```py
rows, cols = len(matrix), len(matrix[0])
copy = [[0 for _ in range(cols)] for _ in range(rows)]
```
Many grid-based games can be modeled as a matrix, such as Tic-Tac-Toe, Sudoku, Crossword, Connect 4, Battleship, etc. It is not uncommon to be asked to verify the winning condition of the game. For games like Tic-Tac-Toe, Connect 4 and Crosswords, where verification has to be done vertically and horizontally, one trick is to write code to verify the matrix for the horizontal cells, transpose the matrix and reuse the logic for horizontal verification to verify originally vertical cells (which are now horizontal).
Transposing a matrix in Python is simply:
```py
transposed_matrix = zip(*matrix)
```
## Corner cases
- Empty matrix. Check that none of the arrays are 0 length
- 1 x 1 matrix
- Matrix with only one row or column
## Recommended LeetCode questions
- [Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes/)
- [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/)
- [Rotate Image](https://leetcode.com/problems/rotate-image/)
- [Word Search](https://leetcode.com/problems/word-search/)

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

@ -1,5 +1,9 @@
Permutation
==
---
id: permutation
title: Permutation
---
## Sample questions
- You are given a 7 digit phone number, and you should find all possible letter combinations based on the digit-to-letter mapping on numeric pad and return only the ones that have valid match against a given dictionary of words.
- Give all possible letter combinations from a phone number.
@ -9,4 +13,4 @@ Permutation
- E.g. when `N` is `3`, we should get `((()))`, `(()())`, `(())()`, `()(())`, `()()()`.
- [Source](http://blog.gainlo.co/index.php/2016/12/23/uber-interview-questions-permutations-parentheses/)
- Given a list of arrays, return a list of arrays, where each array is a combination of one element in each given array.
- E.g. If the input is `[[1, 2, 3], [4], [5, 6]]`, the output should be `[[1, 4, 5], [1, 4, 6], [2, 4, 5], [2, 4, 6], [3, 4, 5], [3, 4, 6]]`.
- E.g. If the input is `[[1, 2, 3], [4], [5, 6]]`, the output should be `[[1, 4, 5], [1, 4, 6], [2, 4, 5], [2, 4, 6], [3, 4, 5], [3, 4, 6]]`.

@ -1,5 +1,9 @@
Queue
==
---
id: queue
title: Queue
---
## Sample questions
- 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).

@ -0,0 +1,17 @@
---
id: recursion
title: Recursion
---
## Notes
Recursion is useful for permutation, because it generates all combinations and tree-based questions. You should know how to generate all permutations of a sequence as well as how to handle duplicates.
Remember to always define a base case so that your recursion will end.
Recursion implicitly uses a stack. Hence all recursive approaches can be rewritten iteratively using a stack. Beware of cases where the recursion level goes too deep and causes a stack overflow (the default limit in Python is 1000). You may get bonus points for pointing this out to the interviewer. Recursion will never be O(1) space complexity because a stack is involved, unless there is [tail-call optimization](https://stackoverflow.com/questions/310974/what-is-tail-call-optimization) (TCO). Find out if your chosen language supports TCO.
## Recommended LeetCode questions
- [Subsets](https://leetcode.com/problems/subsets/) and [Subsets II](https://leetcode.com/problems/subsets-ii/)
- [Strobogrammatic Number II (LeetCode Premium)](https://leetcode.com/problems/strobogrammatic-number-ii/)

@ -1,5 +1,9 @@
Sorting and Searching
==
---
id: sorting-searching
title: Sorting and Searching
---
## Sample questions
- Sorting search results on a page given a certain set of criteria.
- Sort a list of numbers in which each number is at a distance `K` from its actual position.
@ -8,7 +12,6 @@ Sorting and Searching
- Search for an element in a sorted and rotated array.
- [Source](http://blog.gainlo.co/index.php/2017/01/12/rotated-array-binary-search/)
- Sort a list where each element is no more than k positions away from its sorted position.
- Search for an item in a sorted, but rotated, array.
- Merge two sorted lists together.
- Give 3 distinct algorithms to find the K largest values in a list of N items.
- Find the minimum element in a sorted rotated array in faster than O(n) time.

@ -1,5 +1,9 @@
Stack
==
---
id: stack
title: Stack
---
## Sample questions
- Implementation of an interpreter for a small language that does multiplication/addition/etc.
- Design a `MinStack` data structure that supports a `min()` operation that returns the minimum value in the stack in O(1) time.

@ -0,0 +1,100 @@
---
id: string
title: String
---
## Tips
Ask about input character set and case sensitivity. Usually the characters are limited to lowercase Latin characters, for example a to z.
When you need to compare strings where the order isnt important (like anagram), you may consider using a HashMap as a counter. If your language has a built-in Counter class like Python, ask to use that instead.
If you need to keep a counter of characters, a common mistake is to say that the space complexity required for the counter is O(n). The space required for a counter is O(1) not O(n). This is because the upper bound is the range of characters, which is usually a fixed constant of 26. The input set is just lowercase Latin characters.
Common data structures for looking up strings efficiently are
- [Trie/Prefix Tree](https://en.wikipedia.org/wiki/Trie)
- [Suffix Tree](https://en.wikipedia.org/wiki/Suffix_tree)
Common string algorithms are
- [Rabin Karp](https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm) for efficient searching of substring using a rolling hash
- [KMP](https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm) for efficient searching of substring
## Strings are sequences
A string is a sequence of characters. Many tips that apply to arrays also apply to strings.
Are there duplicate characters in the string, would it affect the answer?
When using an index to iterate through characters, be careful not to go out of bounds.
Be mindful about slicing or concatenating strings in your code. Typically, slicing and concatenating strings require O(n) time. Use start and end indices to demarcate a substring where possible.
Sometimes you can traverse the string from the right rather than from the left.
Master the [sliding window technique](https://discuss.leetcode.com/topic/30941/here-is-a-10-line-template-that-can-solve-most-substring-problems) that applies to many substring problems.
When you are given two strings to process, it is common to have one index per string (pointer) to traverse/compare the both of them. For example, we use the same approach to merge two sorted arrays.
## Common question topics
Many string questions fall into one of these buckets.
### Non-repeating Characters
- Use a 26-bit bitmask to indicate which lower case latin characters are inside the string.
```py
mask = 0
for c in set(word):
mask |= (1 << (ord(c) - ord('a')))
```
To determine if two strings have common characters, perform & on the two bitmasks. If the result is non-zero, `mask_a & mask_b > 0`, then the two strings have common characters.
### Anagram
An anagram is word switch or word play. It is the result of re-arranging the letters of a word or phrase to produce a new word or phrase, while using all the original letters only once. In interviews, usually we are only bothered with words without spaces in them.
To determine if two strings are anagrams, there are a few plausible approaches:
- Sorting both strings should produce the same resulting string. This takes O(nlgn) time and O(lgn) space.
- If we map each character to a prime number and we multiply each mapped number together, anagrams should have the same multiple (prime factor decomposition). This takes O(n) time and O(1) space.
- Frequency counting of characters will help to determine if two strings are anagrams. This also takes O(n) time and O(1) space.
### Palindrome
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward as forward, such as _madam_ or _racecar_.
Here are ways to determine if a string is a palindrome:
- Reverse the string and it should be equal to itself.
- Have two pointers at the start and end of the string. Move the pointers inward till they meet. At any point in time, the characters at both pointers should match.
The order of characters within the string matters, so HashMaps are usually not helpful.
When a question is about counting the number of palindromes, a common trick is to have two pointers that move outward, away from the middle. Note that palindromes can be even or odd length. For each middle pivot position, you need to check it twice: Once that includes the character and once without the character.
- For substrings, you can terminate early once there is no match.
- For subsequences, use dynamic programming as there are overlapping subproblems. Check out [this question](https://leetcode.com/problems/longest-palindromic-subsequence/).
## Corner cases
- Empty string
- String with 1 or 2 characters
- String with repeated characters
- Strings with only one distinct character
## Recommended LeetCode questions
- [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/)
- [Longest Repeating Character Replacement](https://leetcode.com/problems/longest-repeating-character-replacement/)
- [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/description/)
- [Valid Anagram](https://leetcode.com/problems/valid-anagram)
- [Group Anagrams](https://leetcode.com/problems/group-anagrams/)
- [Valid Parentheses](https://leetcode.com/problems/valid-parentheses)
- [Valid Palindrome](https://leetcode.com/problems/valid-palindrome/)
- [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring/)
- [Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/)
- [Encode and Decode Strings (LeetCode Premium)](https://leetcode.com/problems/encode-and-decode-strings/)

@ -1,5 +1,7 @@
Topics
==
---
id: topics
title: Topics
---
## Arrays

@ -0,0 +1,61 @@
---
id: tree
title: Tree
---
## Study links
- [Leaf It Up To Binary Trees](https://medium.com/basecs/leaf-it-up-to-binary-trees-11001aaf746d)
## Notes
A tree is an undirected and connected acyclic graph.
Recursion is a common approach for trees. When you notice that the subtree problem can be used to solve the entire problem, try using recursion.
When using recursion, always remember to check for the base case, usually where the node is `null`.
When you are asked to traverse a tree by level, use breadth-first search.
Sometimes it is possible that your recursive function needs to return two values.
If the question involves summation of nodes along the way, be sure to check whether nodes can be negative.
You should be very familiar with writing pre-order, in-order, and post-order traversal recursively. As an extension, challenge yourself by writing them iteratively. Sometimes interviewers ask candidates for the iterative approach, especially if the candidate finishes writing the recursive approach too quickly.
Do check out the section on [Trie](trie.md), which is an advanced tree.
## Corner cases
- Empty tree
- Single node
- Two nodes
- Very skewed tree (like a linked list)
## Special Trees
### Binary Tree
In-order traversal of a binary tree is insufficient to uniquely serialize a tree. Pre-order or post-order traversal is also required.
### Binary Search Tree (BST)
In-order traversal of a BST will give you all elements in order.
Be very familiar with the properties of a BST and validating that a binary tree is a BST. This comes up more often than expected.
When a question involves a BST, the interviewer is usually looking for a solution which runs faster than O(n).
#### Recommended LeetCode questions
- [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/)
- [Same Tree](https://leetcode.com/problems/same-tree/)
- [Invert/Flip Binary Tree](https://leetcode.com/problems/invert-binary-tree/)
- [Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/)
- [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/)
- [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/)
- [Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/)
- [Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/)
- [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)
- [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/)
- [Lowest Common Ancestor of BST](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/)

@ -0,0 +1,23 @@
---
id: trie
title: Trie
---
## Study links
- [Trying to Understand Tries](https://medium.com/basecs/trying-to-understand-tries-3ec6bede0014)
- [Implement Trie (Prefix Tree)](https://leetcode.com/articles/implement-trie-prefix-tree/)
## Notes
Tries are special trees (prefix trees) that make searching and storing strings more efficient. Tries have many practical applications, such as conducting searches and providing autocomplete. It is helpful to know these common applications so that you can easily identify when a problem can be efficiently solved using a trie.
Sometimes preprocessing a dictionary of words (given in a list) into a trie, will improve the efficiency of searching for a word of length k, among n words. Searching becomes O(k) instead of O(n).
Be familiar with implementing, from scratch, a `Trie` class and its `add`, `remove` and `search` methods.
## Recommended LeetCode questions
- [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree)
- [Add and Search Word](https://leetcode.com/problems/add-and-search-word-data-structure-design)
- [Word Search II](https://leetcode.com/problems/word-search-ii/)

@ -1,14 +1,9 @@
Behavioral
==
---
id: behavioral-questions
title: Common Questions
---
Learn the [STAR](https://en.wikipedia.org/wiki/Situation,_task,_action,_result) format. From Wikipedia:
- **Situation** - The interviewer wants you to present a recent challenge and situation in which you found yourself.
- **Task** - What were you required to achieve? The interviewer will be looking to see what you were trying to achieve from the situation. Some performance development methods[1] use “Target” rather than “Task”. Job interview candidates who describe a “Target” they set themselves instead of an externally imposed “Task” emphasize their own intrinsic motivation to perform and to develop their performance.
- **Action** - What did you do? The interviewer will be looking for information on what you did, why you did it and what the alternatives were.
- **Results** - What was the outcome of your actions? What did you achieve through your actions and did you meet your objectives? What did you learn from this experience and have you used this learning since?
## General
### General
- Why do you want to work for X company?
- Why do you want to leave your current/last company?
@ -28,9 +23,10 @@ Learn the [STAR](https://en.wikipedia.org/wiki/Situation,_task,_action,_result)
- 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?
- What is something you had to persevere at for multiple months?
- Tell me about a time you met a tight deadline.
## Airbnb
### Airbnb
Source: [Glassdoor](https://www.glassdoor.com/Interview/Airbnb-Interview-Questions-E391850.htm)
@ -43,9 +39,9 @@ While loving to travel or appreciating Airbnb's growth may be good answers, try
- 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?
- What is something that you don't want from your last internship/job?
- Give me an example of when you've been a good host.
- One thing you would like to remove from the Airbnb experience.
- What's something you'd like to remove from the Airbnb experience?
- What is something new that you can teach your interviewer in a few minutes?
- Tell me about why you want to work here.
- What is the best gift you have ever given or received?
@ -61,20 +57,20 @@ While loving to travel or appreciating Airbnb's growth may be good answers, try
- How does Airbnb impact our guests and hosts?
- What part of our mission resonates the most with you?
## Amazon
### Amazon
Source: [Glassdoor](https://www.glassdoor.com/Interview/Amazon-Interview-Questions-E6036.htm)
- How do you deal with a failed deadline?
- Why do you want to work for Amazon?
- Talked about a situation where you had a conflict with a teammate.
- In my professional experience have you worked on something without getting approval from your manager?
- Tell me about a situation where you had a conflict with a teammate.
- In your professional experience have you worked on something without getting approval from your manager?
- Tell me a situation where you would have done something differently from what you actually did.
- What is the most exceedingly bad misstep you at any point made?
- Describe what Human Resource means to you.
- What is the most exceedingly bad misstep you've made at any point?
- Describe what Human Resources means to you.
- How would you improve Amazon's website?
## Dropbox
### Dropbox
Source: [Glassdoor](https://www.glassdoor.com/Interview/Dropbox-Interview-Questions-E415350.htm)
@ -82,7 +78,7 @@ Source: [Glassdoor](https://www.glassdoor.com/Interview/Dropbox-Interview-Questi
- If you were hired here what would you do?
- State an experience about how you solved a technical problem. Be specific about the diagnosis and process.
## Hired
### Hired
Source: [Glassdoor](https://hired.com/blog/candidates/10-top-interview-questions-how-to-answer/)
@ -91,41 +87,40 @@ Source: [Glassdoor](https://hired.com/blog/candidates/10-top-interview-questions
- Why are you interested in this opportunity?
- What are your salary expectations?
- Why are you looking to leave your current company?
- What is your biggest strength and area of growth?
- Tell me about a time your work responsibilities got a little overwhelming. What did you do?
- Give me an example of a time when you had a difference of opinion with a team member. How did you handle that?
- Tell me about a challenge you faced recently in your role. How did you tackle it? What was the outcome?
- Where do you want to be in five years?
- Tell me about a time you needed information from someone who wasn't responsive. What did you do?
## Lyft
### Lyft
Source: [Glassdoor](https://www.glassdoor.com/Interview/Lyft-Interview-Questions-E700614.htm)
- Tell me about your most interesting/challenging project to date.
- Why Lyft? What are you looking for in the next role?
## Palantir
### Palantir
Source: [Glassdoor](https://www.glassdoor.com/Interview/Palantir-Technologies-Interview-Questions-E236375.htm)
- **What is something 90% of people disagree with you about?**
- **What is broken around you?**
- How do you deal with difficult coworkers? Think about specific instances where you resolved conflicts.
- How did you win over the difficult employees?
- Tell me about an analytical problem that you have worked on in the past.
- What are your three strengths and three weaknesses?
- If you were in charge of picking projects for Palantir, what problem would you try to solve?
- **What is something 90% of people disagree with you about?**
- What are some of the best and worse things about your current company?
- **What is broken around you?**
- What are some of the best and worst things about your current company?
- What would your manager say about you?
- Describe Palantir to your grandmother.
- Teach me something you've learned?
- Tell me a time when you predicted something?
- If your supervisors were to rate you on a scale of 1-10 what would they rate you?
- Teach me something you've learned.
- Tell me a time when you predicted something.
- If your supervisors were to rate you on a scale of 1-10, what would they rate you?
- What was the most fun thing you did recently?
- Tell me the story of how you became who you are today and what made you apply to Palantir.
## Slack
### Slack
Source: [Glassdoor](https://www.glassdoor.com/Interview/Slack-Interview-Questions-E950758.htm)
@ -133,13 +128,13 @@ Source: [Glassdoor](https://www.glassdoor.com/Interview/Slack-Interview-Question
- Why do you want to join Slack?
- Tell me about your past projects.
- Explain me your toughest project and the working architecture.
- Apart from technical knowledge what did you learn during your internship?
- Apart from technical knowledge, what did you learn during your internship?
- If someone has a different viewpoint to do a project like different programming language, how would handle this situation?
- What are your most interesting subjects and why?
- Did you find any bug in Slack?
- Did you find any bugs in Slack?
- What is your favorite feature and why?
## Stack Overflow
### Stack Overflow
Source: [Glassdoor](https://hired.com/blog/candidates/10-top-interview-questions-how-to-answer/)
@ -148,9 +143,9 @@ Source: [Glassdoor](https://hired.com/blog/candidates/10-top-interview-questions
- How did you solve it?
- Where do you see yourself in 5 years?
- Why do you want to work here?
- How do you handle disagreements with coworkers?
- How do you handle disagreements with co-workers?
## Stripe
### Stripe
Source: [Glassdoor](https://www.glassdoor.com/Interview/Stripe-Interview-Questions-E671932.htm)
@ -158,7 +153,7 @@ Source: [Glassdoor](https://www.glassdoor.com/Interview/Stripe-Interview-Questio
- Explain a project that you worked on recently that was difficult.
- Where do you see yourself in five years?
## Twitter
### Twitter
Source: [Glassdoor](https://www.glassdoor.com/Interview/Twitter-Interview-Questions-E100569.htm)

@ -0,0 +1,22 @@
---
id: behavioral-round-overview
title: Overview
---
Succeeding in an engineering career involves more than just technical skills. Behavioral interviews (aka people skills) become more important as an engineer becomes more senior. Senior engineers should have the ability to lead and influence, resolve conflicts, anticipate risks, plan the roadmap, and more.
Hiring a talented engineer that cannot work with others can ultimately be a net deficit for companies. Companies dont want to hire [brilliant jerks](http://www.brendangregg.com/blog/2017-11-13/brilliant-jerks.html). The company is better off not hiring a very talented engineer who refuses to work with others or causes an entire team to be unproductive. Companies want to hire the right person that will work well with the existing employees and help the team and company achieve greater heights, and behavioral interviews are one way of determining if someone will be good to work with from a non-technical standpoint.
## Most companies evaluate behavioral skills
Companies value behavioral skills and do evaluate candidates on them. At the time of writing, Facebook has one round (out of four) dedicated to behavioral interviews. Airbnb has TWO rounds (out of six) dedicated to behavioral interviews/company fit. Lyft has one round (out of five) dedicated to past experience and situational questions by a hiring manager.
## What Facebook looks for in behavioral interviews
- Discuss anything written on your resume, and be able to go in-depth
- Provide specific examples about what you did and the resulting impact
- Critique yourself and share what you learned from a past situation
- Talk about what you like about your current role and/or being a developer
- Discuss what and why changes you would like to make
_Source: [Preparing for your Onsite Interview at Facebook](https://www.facebook.com/careers/swe-prep-onsite)_

@ -0,0 +1,107 @@
---
id: best-practice-questions
title: Best Practice Questions
---
Here is a suggested schedule for revising and practicing algorithm questions on [LeetCode](https://leetcode.com). Sign up for an account if you don't already have one, it's critical to your success in interviewing!
When practicing, you are advised to treat it like a real coding interview and check through thoroughly before submitting. Consider even manually coming up with some test cases and running through them to verify correctness!
## Week 1 - Sequences
In week 1, we will start off easy and do a mix of easy and medium questions on arrays and strings. Arrays and strings are the most common types of questions to be found in interviews; gaining familiarity with them will help in building strong fundamentals to better handle tougher questions.
- [Two Sum](https://leetcode.com/problems/two-sum/)
- [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/)
- [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)
- [Valid Anagram](https://leetcode.com/problems/valid-anagram/)
- [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)
- [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/)
- [Maximum Subarray](https://leetcode.com/problems/maximum-subarray/)
- [3Sum](https://leetcode.com/problems/3sum/)
- [Merge Intervals](https://leetcode.com/problems/merge-intervals/)
- [Group Anagrams](https://leetcode.com/problems/group-anagrams/)
#### Optional
- [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray/)
- [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/)
## Week 2 - Data Structures
The focus of week 2 is on linked lists, strings and matrix-based questions. The goal is to learn the common routines dealing with linked lists, traversing matrices and sequence analysis (arrays/strings) techniques such as sliding window.
- [Reverse a Linked List](https://leetcode.com/problems/reverse-linked-list/)
- [Detect Cycle in a Linked List](https://leetcode.com/problems/linked-list-cycle/)
- [Container With Most Water](https://leetcode.com/problems/container-with-most-water/)
- [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/)
- [Longest Repeating Character Replacement](https://leetcode.com/problems/longest-repeating-character-replacement/)
- [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/)
- [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring/)
- [Number of Islands](https://leetcode.com/problems/number-of-islands/)
- [Remove Nth Node From End Of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/)
- [Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings/)
- [Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow/)
## Week 3 - Non-Linear Data Structures
The focus of week 3 is on non-linear data structures like trees, graphs and heaps. You should be familiar with the various tree traversal (in-order, pre-order, post-order) algorithms and graph traversal algorithms such as breadth-first search and depth-first search. In my experience, using more advanced graph algorithms (Dijkstra's and Floyd-Warshall) is quite rare and usually not necessary.
- [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/)
- [Invert/Flip Binary Tree](https://leetcode.com/problems/invert-binary-tree/)
- [Non-overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals/)
- [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree/)
- [Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/)
- [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/)
- [Clone Graph](https://leetcode.com/problems/clone-graph/)
- [Course Schedule](https://leetcode.com/problems/course-schedule/)
- [Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum/)
#### Optional
- [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree/)
- [Same Tree](https://leetcode.com/problems/same-tree/)
- [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/)
- [Encode and Decode Strings (LeetCode Premium)](https://leetcode.com/problems/encode-and-decode-strings/)
## Week 4 - More Data Structures
Week 4 builds up on knowledge from previous weeks but questions are of increased difficulty. Expect to see such level of questions during interviews. You get more practice on more advanced data structures such as (but not exclusively limited to) heaps and tries.
- [Add and Search Word](https://leetcode.com/problems/add-and-search-word-data-structure-design/)
- [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/)
- [Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree/)
- [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/)
- [Lowest Common Ancestor of BST](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/)
- [Merge K Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists/)
- [Find Median from Data Stream](https://leetcode.com/problems/find-median-from-data-stream/)
- [Insert Interval](https://leetcode.com/problems/insert-interval/)
- [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/)
- [Word Search II](https://leetcode.com/problems/word-search-ii/)
#### Optional
- [Meeting Rooms (LeetCode Premium)](https://leetcode.com/problems/meeting-rooms/)
- [Meeting Rooms II (LeetCode Premium)](https://leetcode.com/problems/meeting-rooms-ii/)
- [Alien Dictionary (LeetCode Premium)](https://leetcode.com/problems/alien-dictionary/)
- [Graph Valid Tree (LeetCode Premium)](https://leetcode.com/problems/graph-valid-tree/)
- [Number of Connected Components in an Undirected Graph (LeetCode Premium)](https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/)
## Week 5 - Dynamic Programming
Week 5 focuses on Dynamic Programming (DP) questions. Personally as an interviewer, I'm not a fan of DP questions as they are not really applicable to practical scenarios and frankly if I were made to do the tough DP questions during my interviews I'd not have gotten the job. However, companies like Google still ask DP questions and if joining Google is your dream, DP is unavoidable.
DP questions can be hard to master and the best way to get better at them is... you guessed it - practice! Be familiar with the concepts of memoization and backtracking.
Practically speaking the return of investment (ROI) on studying and practicing for DP questions is very low. Hence DP questions are less important/optional and you should only do them if you're very keen to have all bases covered.
- [Climbing Stairs](https://leetcode.com/problems/climbing-stairs/)
- [Coin Change](https://leetcode.com/problems/coin-change/)
- [Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence/)
- [Combination Sum](https://leetcode.com/problems/combination-sum-iv/)
- [House Robber](https://leetcode.com/problems/house-robber/)
- [House Robber II](https://leetcode.com/problems/house-robber-ii/)
- [Decode Ways](https://leetcode.com/problems/decode-ways/)
- [Unique Paths](https://leetcode.com/problems/unique-paths/)
- [Jump Game](https://leetcode.com/problems/jump-game/)
- [Word Break Problem](https://leetcode.com/problems/word-break/)

@ -0,0 +1,107 @@
---
id: cheatsheet
title: 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.
#### Legend
- ✅ = Do
- ❌ = Don't
- ⚠️ = Situational
### 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 behavioral questions](behavioral-questions.md) in an interview. |
| ✅ | Prepare some [questions to ask](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. |
### 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. |
### Upon receiving the question
| | Things |
| --- | --- |
| ✅ | Repeat the question back at the interviewer. |
| ✅ | Clarify any assumptions you made subconsciously. Many questions are under-specified on purpose. E.g. 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/introduction.md) 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. |
### 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., "Under non-interview settings, 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 or single-character (unless they're common like `i`, `n`) variable names. |
| ❌ | Copy and paste code without checking (e.g. variables need to be renamed). |
| ❌ | 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. |
### 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. |
### Wrap up
| | Things |
| --- | --- |
| ✅ | Ask questions. More importantly, ask good and engaging questions that are tailored to the company! Pick some questions from [this list](questions-to-ask.md). |
| ✅ | Thank the interviewer. |
| ⚠️ | Ask about your interview performance. It can get awkward. |
| ❌ | End the interview without asking any questions. |
### 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,14 @@
---
id: coding-round-overview
title: Overview
---
Coding interviews are tough. But fortunately, there's a tried and proven method to get better at them. With a combination of studying, practicing questions and doing mock interviews, getting that dream job can become a reality.
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. Know what [signals and behaviors](./coding-signals.md) interviewers are looking out for
1. Practice doing mock interviews
1. Interview successfully to get the job

@ -0,0 +1,96 @@
---
id: coding-signals
title: Coding Signals
---
The point of interviews is for interviewers to extract signals from certain candidate behaviors. In coding interviews, the signals can be broadly classified into the following categories: Problem Solving, Technical Competency, Testing, and Communication.
When interviewers take down interview feedback, these are likely what is on their feedback sheet.
## Problem solving
#### Understanding the problem
- 👍 Understood the key aspects of the problem quickly
- 👎 Had difficulty in understanding the key aspects of the problem
#### Solution/approach
- 👍 Approached the problem in a systematic and logical manner
- 👎 Did not demonstrate a logical thought process for approaching the problem
#### Improving the solution
- 👍 Suggested a more efficient solution when prompted, or proactively coming up with a better solution
- 👎 Had difficulty in coming up with a more efficient solution even after being prompted
#### Trade-offs analysis
- 👍 Explained the trade-offs of different approaches clearly and correctly
- 👎 Failed to describe trade-offs of different approaches
#### Hinting
- 👍 Did not require any major hints
- 👎 Needed plenty of hints
## Technical competency
#### Speed
- 👍 Quickly implemented a working solution
- 👎 Was not able to complete the solution
#### Correctness/Accuracy
- 👍 Implemented the solution correctly (e.g., working solution, minimal bugs)
- 👎 Unable to correctly implement a solution (e.g., non-working solution, incorrect logic, and/or serious bugs)
#### Complexity analysis
- 👍 Able to determine the algorithmic time and space complexity
- 👎 Was not able to determine the algorithmic time and space complexity (explain why TC came up with such an answer)
#### Mastery of chosen programming language
- 👍 Demonstrated mastery of the chosen programming language
- 👎 Does not seem to be familiar with the chosen programming language
#### Implementation
- 👍 Implementation was clean and straightforward
- 👎 Implementation was unnecessarily complex and/or messy
#### Coding style
- 👍 Coding style was neat (proper indentation, spacing and no bad practices)
- 👎 Coding style was messy (inconsistent indentation, weird spacings, etc)
## Testing
#### Common cases
- 👍 Tested their code against various typical cases
- 👎 Failed to test the code against typical cases
#### Corner cases
- 👍 Found and handled corner/edge cases
- 👎 Failed to consider corner/edge cases
#### Self-correction
- 👍 Identified and corrected bugs in the code (where applicable)
- 👎 Was not able to discover and fix bugs even after being prompted
## Communication
#### Clarify problem
- 👍 Appropriately asked good, clarifying questions about the problem
- 👎 Failed to confirm understanding/ask appropriate questions
#### Communicating approach
- 👍 Able to explain overall approach, technical terms and acronyms (where applicable)
- 👎 Failed to effectively explain overall approach, technical terms and acronyms (where applicable)

@ -1,5 +1,7 @@
Cover Letter
==
---
id: cover-letter
title: Cover Letter
---
- A short introduction describing who you are and what you're looking for.
- What projects have you enjoyed working on?

@ -0,0 +1,78 @@
---
id: during-coding-interview
title: During the Coding Interview
---
Congratulations, you are ready to put your skills into practice! In a real coding interview, you will be given a technical question by the interviewer, write code in a real-time collaborative editor (phone screen) or on a whiteboard (on-site) to solve the problem within 3045 minutes. This is where the real fun begins!
Your interviewer will be looking out for signals that you fit the requirements of the role and it is up to you to display those signals to them. Initially it may feel weird to be talking while you are coding as most programmers do not have the habit of explaining out loud as they are typing code. However, it is hard for the interviewer to know what you are thinking just by looking at the code that you type. If you communicate your approach to the interviewer before you start coding, you can validate your approach with them and the both of you can agree upon an acceptable approach.
## Before the interview (remote)
For phone screens/remote interviews, prepare paper and pen/pencil to jot down and visualize stuff. If you are given a question on trees and graphs, it usually helps if you draw out some examples of the data structure given in the question.
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
Prepare a self introduction by following the [self introduction section](./self-introduction.md).
## Upon receiving 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. Repeating back/rephrasing the question will reduce chances of miscommunication.
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.
Some common questions you can ask:
- How big is the size of the input?
- How big is the range of values?
- What kind of values are there? Are there negative numbers? Floating points? Will there be empty inputs?
- Are there duplicates within the input?
- What are some extreme cases of the input?
- Can I destroy the original array/graph/data structure?
- How is the input stored? If you are given a dictionary of words, is it a list of strings or a Trie?
After you have sufficiently clarified the scope and intention of the problem, explain your high level approach to the interviewer even if it is a naive solution. If you are stuck, consider various approaches and explain out loud why it will/will not work. Sometimes your interviewer might drop hints and lead you towards the right path.
Start with a brute force approach, communicate it to the interviewer, explain the time and space complexity and why it is bad. It is unlikely that the brute force approach will be one that you will be coding. At this point, the interviewer will usually pop the dreaded "Can we do better?" question, meaning that they are looking for a more optimal approach. In my opinion, this is usually the hardest part of the interview. In general, look for repeated work and try to optimize them by potentially caching the calculated result somewhere and reference it later, rather than having to compute it all over again. There are some tips on tackling topic-specific questions that I dive into details below.
Only start coding after you and your interviewer have agreed on an approach and they have given you the green light.
## What to do when stuck
Getting stuck during coding interviews is extremely common. But do not worry, that is part of the process and is a test of your problem solving abilities. Here are some tips to try out when you are stuck:
- Talk through what you initially thought might work and explain why it doesn't
- This can help guide you on the right track by avoiding the pitfalls
- Come up with more test cases and write them down
- A pattern may emerge
- Think about how you would solve it without a program
- You may spot a pattern and come up with a general algorithm for it
- Recall past questions related to the topic, what similar questions in the past have you encountered and what techniques did you use?
- Enumerate through the common data structures and whether they can be applied to the question
- Dictionaries/maps are extremely common in making algorithms more efficient
- Look out for repeated work and determine if you can cache those computations
- Trade off memory for speed
## While coding
Write your code with good coding style. Reading code written by others is usually not an enjoyable task. Reading horribly-formatted code by others makes it worse. Your goal is to make your interviewer understand the code you have written so that they can quickly evaluate if your code does what you say it does and whether it solves the given problem. Use clear variable names, avoid single letter names unless they are for iteration. However, if you are coding on a whiteboard, you might not want to use extremely verbose variable names for the sake of reducing the amount you have to write. Abbreviations are usually fine if you explain what it means beforehand.
Always be explaining what you are currently writing/typing to the interviewer. This is not about literally reading out what you are typing to the interviewer. Talk about the section of the code you are currently implementing at a higher level, explain why it is written as such and what it is trying to achieve.
While coding, if you find yourself copying and pasting code, consider whether it is necessary. If you find yourself copying and pasting one large chunk of code spanning multiple lines, it is usually an indicator that you can refactor by extracting those lines into a function and defining parameters for the differences in them. If it is just a single line you copied, usually it is fine. Do remember to change the respective variables in your copied line of code where relevant. Copy-paste errors are a common source of bugs even in day-to-day coding!
## After coding
After you have finished coding, do not immediately announce to the interviewer that you are done. In most cases, your code is usually not perfect and contains some bugs or syntax errors. What you need to do now is to review your code.
Firstly, look through your code from start to finish as if it is the first time you are seeing it, as if it was written by someone else and you are trying to spot bugs in it. That's exactly what your interviewer will be doing. Look through and fix any minor issues you may find.
Next, come up with small test cases and step through the code (not your algorithm!) with those sample input. What interviewers usually do after you have finished coding would be to get you to write tests. It is a huge plus if you write tests for your code even before they prompt you to do so. You should be emulating a debugger when stepping through and jot down or say out the values of the important variables as you step through the lines of code.
If there are huge duplicated chunks of code in your solution, it would be a good chance to refactor it and demonstrate to the interviewer that you are one who values code quality. Also look out for places where you can do [short-circuit evaluation](https://en.wikipedia.org/wiki/Short-circuit_evaluation).
Lastly, give the time/space complexity of your code and explain why it is such. You can even annotate certain chunks of your code with the various time/space complexities to demonstrate your understanding of your code and the APIs of your chosen programming language. Explain any trade-offs in your current approach vs alternative approaches, possibly in terms of time/space.
If your interviewer is happy with the solution, the interview usually ends here. It is also not uncommon that the interviewer asks you extension questions, such as how you would handle the problem if the whole input is too large to fit into memory, or if the input arrives as a stream. This is a common follow-up question at Google where they care a lot about scale. The answer is usually a divide-and-conquer approachperform distributed processing of the data and only read certain chunks of the input from disk into memory, write the output back to disk, and combine them later on.

@ -0,0 +1,16 @@
---
id: how-to-apply
title: How to Apply
---
## Apply Directly
TODO
## Referrals
TODO
## Agencies/Portals
TODO

@ -0,0 +1,162 @@
---
id: interview-formats
title: Interview Formats
---
Interviews are a multi-stage process and each stage can consist of vastly different formats.
## Various formats
### Pop quiz
Pop quizzes are meant to be a quick and dirty way of weeding out extremely weak (or even non-technical) candidates. They are structured questions and have clear-cut answers which makes them possible to be administered by recruiters/non-technical folks. It is not a very common interview format these days.
Examples:
- What is 4 & 5 (in binary)? Answer: 4
- What is the time complexity of bubble sort? Answer: O(n^2)
### Take home assignment
There has been numerous debates on whether asking algorithm questions are a good way of assessing individual abilities as they aren't exactly the most relevant skills needed for a job. Take home assignment is a format designed to address the shortcomings of the algorithm interview by getting candidates to work on larger projects which allow them to demonstrate software design skills.
However, this interview format takes up more time from both the candidates and the company and hence it is not as commonly seen in large companies where they have a high volume of candidates. This format is more common among startups and small companies.
Examples
- Build a flights listing app
- Build a snake game
### Phone interview
Phone interviews are the most common format and every candidate will face this at least once while interviewing. You will be asked to speak with an interviewer either over a phone call or VoIP (Skype/Hangout). A question will be given to you and you will work on that question using an online collaborative editor (CoderPad/CodePen/Google Docs).
You are usually not allowed to execute the code even if the editor supports execution. So don't rely on that for verifying the correctness of your solution. Formats would differ slightly depending on the roles you are applying to. Many companies like to use [CoderPad](https://coderpad.io/) for collaborative code editing. CoderPad supports running of the program, so it is possible that you will be asked to fix your code such that it can be run. For front end interviews, many companies like to use [CodePen](https://codepen.io/), and it will be worth your time to familiarize yourself with the user interfaces of such web-based coding environments.
### Onsite
If you have made it to this stage, congratulations! This is usually the final stage before an offer decision. Candidates who made it to the onsite stage will be required to have an in-person interview at the office. If you are an overseas candidate, companies might even fly you in and pay for your accommodations!
The onsite stage usually consists of multiple rounds (coding, system design, behavioral) and is expected to last for a few hours. Since you are onsite, it is possible that you will be asked to do a whiteboard exercise with an interviewer, usually either solving an algorithm question or doing a system design question. It is also possible that you have to bring your own laptops and work on a project/solve a coding problem on the spot.
For onsite interviews at smaller (non-public) companies, most will allow (and prefer) that you use your own laptop. Hence it is important that you prepare your development environment in advance.
If the company provides lunch, you might also have a lunch session with an employee where you can find out more about the company culture.
## Formats of famous companies
### Airbnb
- Recruiter phone screen
- Technical phone interview:
- 1 or 2 x Algorithm/front end on CoderPad/CodePen
- On-site (General):
- 2 x Algorithm coding on CoderPad
- 1 x System design/architecture
- 1 x Past experience/project
- 2 x Cross functional
- On-site (Front End):
- 2 x Front end coding on CodePen. Use any framework/library
- 1 x General coding on your own laptop
- 1 x Past experience/project
- 2 x Cross functional
- Tips:
- All sessions involve coding on your own laptop. Prepare your development environment in advance
- You are allowed to look up APIs if you need to
- They seem to place high emphasis on compilable, runnable code in all their coding rounds
- Cross functional interviews will involve getting Airbnb employees from any discipline to speak with you. These interviews are mostly non-technical but are extremely important to Airbnb because they place a high emphasis on cultural fit. Do look up the Airbnb section of the behavioral questions to know what sort of questions to expect
### Asana
- Recruiter phone screen
- Technical phone interview
- On-site (Product Engineer):
- 3 x Algorithm and system design on whiteboard within the same session
- 1 x Algorithm on laptop and system design. This session involves writing code on your own laptop to solve 3 well-defined algorithm problems in around 45 minutes after which an engineer will come in and review the code with you. You are not supposed to run the code while working on the problem
- Tips:
- No front end questions were asked
- Asana places high emphasis on System Design and makes heavy use of the whiteboard. You do not necessarily have to write code for the algorithm question of the first three interviews
- All 4 sessions involve algorithms and system design. One of the sessions will be conducted by an Engineering Manager
- The last session will involve coding on your own laptop. Prepare your development environment in advance
- Regardless of Product Engineer or Engineering Generalist position, their interview format and questions are similar
### Dropbox
- Recruiter phone screen
- Technical phone interviews:
- 2 x Algorithm/front end on CoderPad/CodePen
- On-site (Front End):
- 2 x Front end on CodePen. Only Vanilla JS or jQuery allowed
- 1 x General coding on CoderPad
- 1 x All around. Meet with an Engineering Manager and discussing past experiences and working style
- Tips:
- You can code on your own laptop and look up APIs
- Dropbox recruiters are very nice and will give you helpful information on what kind of questions to expect for the upcoming sessions
- One of the front end sessions involve coding up a pixel-perfect version of a real page on www.dropbox.com. You'll be given a spec of the desired page and you'll be asked to create a working version during the interview
### Facebook
- Recruiter phone screen
- Technical phone interviews:
- 1 or 2 x Algorithm/front end on Skype/CoderPad
- On-site (Front End):
- 2 x Technical coding interview on whiteboard (Ninja)
- 1 x Behavioural (Jedi). Meet with an Engineering Manager and discussing past experiences and working style
- 1 x Design/architecture on whiteboard (Pirate)
- Tips:
- You are only allowed to use the whiteboard (or wall). No laptops involved
- For the Jedi round, you may be asked a technical question at the end of it. Front end candidates will be given a small HTML/CSS problem nearing the end of the session
- For the Ninja rounds, you may be asked one to two questions depending on how fast you progress through the question
### Google
- Recruiter phone screen
- Technical phone interview:
- 1 or 2 x algorithm on Google Doc
- On-site:
- 1 or 2 x Front end on whiteboard. May be required to use Vanilla JS (or at the most, jQuery) depending on the question. (Front End only)
- 2 to 4 x Algorithm on whiteboard
- 1 x General Cognitive Ability, Leadership and "Googleyness".
- Team matching
- Speak with managers from different teams who are interested in your profile
- Tips:
- In rare cases, candidates may even be allowed to skip the phone interview round and advanced to on-site directly
- For non-fresh grads, you only receive an offer if you are successfully matched with a team
### Lyft
- Recruiter phone screen
- Technical phone interview:
- 1 x Algorithm/Front end over JSFiddle
- On-site (Front End):
- 4 x Front end on Coderpad/your own laptop. Use any language/framework
- 1 x Behavioral. Meet with an Engineering Manager and go through candidate's resume
- Tips:
- Can use whiteboard and/or laptop
- For front end coding, I opted to use React and had to set up the projects on the spot using `create-react-app`
### Palantir
- Recruiter phone screen
- Technical phone interview:
- 1 x Algorithm over HackerRank CodePair and Skype
- On-site (General):
- 2 x Algorithm on whiteboard
- 1 x Decomposition (system design) on whiteboard
- On-site (Front End):
- 1 x Front end on your own laptop. This session lasts about 1.5 hours. Use any library/framework
- 1 x Decomposition (system design) on whiteboard
- Tips:
- I opted to use React and had to set up projects on the spot using `create-react-app`
- You may be asked to meet with Engineering Managers after the technical sessions and it's not necessarily a good/bad thing
### WhatsApp
- Recruiter phone screen
- Technical phone interview:
- 2 x Algorithm over CoderPad
- On-site (Web Client Developer):
- 4 x Algorithm on whiteboard
- Tips:
- No front end questions were asked
- 1 of the interviewers is an Engineering Manager

@ -0,0 +1,76 @@
---
id: interviewer-cheatsheet
title: Cheatsheet (Interviewer)
---
This is a straight-to-the-point, distilled list of technical interview Do's and Don'ts **for interviewers**, 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 as an interviewer to remind myself of them and eventually internalized all of them to the point I do not have to rely on it anymore.
**If you are a candidate you probably do not need to know this section well. You may read this to get a better sense of what an interviewer is supposed to do during an interview.**
#### Legend
- ✅ = Do
- ❌ = Don't
- ⚠️ = Situational
### Before interview
| | Things |
| --- | --- |
| ✅ | Make sure your surroundings are well-lit. |
| ✅ | Find a quiet environment with good Internet connection. |
| ✅ | Ensure webcam and audio are working. Test that your VC app is working well. |
| ✅ | Prepare two to three questions and be familiar with the different approaches for solving the questions. |
| ✅ | Familiarize yourself with the coding environment (CoderPad/CodePen). Set up the coding shortcuts, turn on autocompletion, tab spacing, etc. |
### Introduction
| | Things |
| --- | --- |
| ✅ | Check if candidate wants to use the restroom or take a break. |
| ✅ | Give an overview of the interview format (introduction, duration, programming languages available, 5 min at the end for Q&A). |
| ✅ | Do a self-introduction and get the candidate to introduce themselves. |
| ✅ | Explain to candidate that they do not have to finish all questions and you might interrupt them abruptly. |
| ❌ | Allow the candidate to spend too long introducing themselves. |
### Upon delivering the question
| | Things |
| --- | --- |
| ✅ | Ask if the candidate has seen the question before. |
| ✅ | Give a small example for the question and the desired output. |
| ✅ | Get the candidate to talk through the solution first before diving into coding. |
| ✅ | Provide hints where appropriate. |
| ✅ | If candidate is still stuck after providing hints, provide the solution and move to coding so that you can get coding signals. |
### During coding
| | Things |
| --- | --- |
| ✅ | If whiteboard interview, stand alongside candidate but also giving them space, instead of being distant, e.g seated down. |
| ✅ | Take note of all the positive and negative signals. |
| ❌ | Check the time in an overly-obvious manner. |
### After coding
| | Things |
| --- | --- |
| ✅ | Ask for candidate to provide test cases and run through the code with them. |
| ✅ | Point out edge cases candidate missed and ask the candidate to address them. |
| ✅ | Take note of the duration TC spent on each question to include in the feedback. |
| ✅ | Ask for time complexity and space analysis. |
| ✅ | Preserve the code somewhere - take a picture or copy the code out. |
| ✅ | Stop the candidate when there is 5 minutes left. e.g. ("I'll stop you here and let's go to the next section") |
### Wrap up
| | Things |
| --- | --- |
| ✅ | Allow candidate to ask questions and answer them to the best of your ability. |
| ✅ | Thank the candidate and wish them all the best. |
### Post interview
| | Things |
| --- | --------------------------------------------------------- |
| ✅ | Write feedback as soon as possible to not forget details. |

@ -0,0 +1,16 @@
---
id: introduction
title: Introduction
---
## What is this?
The **Tech Interview Handbook** contains carefully curated content to help you ace your next technical interview with a focus on algorithms. While there are a ton of interview resources on the internet, the best ones are either not free, or they do not cover the complete interview process, usually only focusing on algorithms.
## Why do I want this?
This repository has **practical** content that covers all phases of a technical interview, from applying for a job to passing the interviews to offer negotiation. Technically competent candidates might still find the non-technical content helpful as well.
## Who is this for?
Whether you are a beginner to technical interviews or a seasoned engineer who have not been on the other side of the interviewing table in a while and want to get back into the game, the Tech Interview Handbook has got you covered.

@ -0,0 +1,61 @@
---
id: landscape
title: Landscape
---
import useBaseUrl from '@docusaurus/useBaseUrl';
Most of the content covered here will be specific to the Bay Area. Landscape differences due to geographical location are mentioned briefly [below](#geographical-location).
## Career prospects as a Software Engineer
### High demand
Almost every domain leverages on technology, hence Software Engineers are needed in almost every industry. Demand for engineers is higher than supply, leading to generally high-paying jobs. Moreover, the demand is continuously growing.
### Stable career
Computer Science is rapidly gaining popularity and engineering is a highly-regarded professional career. Unlike the creative industry, you do not have to be the top 1% of the industry to lead a comfortable life. An engineer fresh out of college working at a Silicon Valley company (both large companies and startups) can expect to receive a starting salary of more than USD 100,000 and it just gets better from there.
### Require lifelong learning
Technology industry is an extremely fast-moving one. Many technologies used today didn't even exist/were popular a decade ago; in 2009, mobile app development and blockchain were pretty much unheard of. Engineers constantly need to upgrade their skills to stay relevant to the demands of the job market. Engineering is a great career for passionate individuals who like to learn.
### Flexible
A software engineering job is perhaps the most flexible job that exists in terms of hours, location and environment. Physical location is usually not an issue and there are many tech companies that are fully remote. There's no formal attire to be worn and working hours are generally flexible. Your co-workers would stare at you weirdly if you came to work wearing a shirt and tie.
## Internships vs full-time
If you dream of working at a top-tier tech company one day, getting hired via an intern conversion is by far the easiest way to achieve that. Internship interviews are extremely short (usually just 2 rounds whereas interviews for full-time roles are usually 4-5 rounds). Internships allow you to work at a company over a short period of time (3 months or so) and helps in understanding the company and engineering culture better. Companies also tend to give higher return job offers to high performing interns as they have proven to be effective at the job and fits into the culture; hence hiring them is considered to be relatively low-risk.
Top tech companies pay a ridiculous amount for interns:
<div class="text--center">
<img src={useBaseUrl('/img/internship-salaries.jpg')} />
_Salaries of top tech internships in 2016 ([source](https://twitter.com/rodneyfolz/status/724787290824798209))_
</div>
## Company size
Companies have different focuses depending on the stage they are at and the types of work to be done can also be vastly different. In the earlier stages where product-market fit hasn't been found, companies would be rapidly iterating on products and features, whereas larger companies that have already found the right product will focus on scaling their infrastructure and growing their users. Liquid compensation is also lower at early-stage companies due to the equity not being worth any money, but there is the chance of earning a lot more if/when the company IPOs or gets acquired.
| | Early-stage Startup | Late-stage Startup | Large Company |
| --- | --- | --- | --- |
| Company Size | <100 | 100-1000 | >1000 |
| Compensation | Base salary is a bit higher than big companies. Higher equity amount but its value is hard to judge as the company's valuation is unclear and stocks are not worth money yet. | Base salary is a bit higher than big companies. Company valuation is clearer and stocks have higher chance of being worth money. | Depends on the prestige of the company. Compensation is usually market standard or better. Stocks are worth money if company has gone public. |
| Types of Work | Mainly product development. Engineers have to wear multiple hats - Front End, Back End, DevOps, Design, etc. | Product development and some infra. | Diverse roles and specialized work; dedicated people for each role. Infra work is more common. Also more opportunities for internal transfers. |
| Career Ladders | Unstructured. No (or very vague) career levels. No formal mentorship nor training. | Somewhat structured. | Very structured. Well-defined career levels. |
| Iteration Speed | Extremely fast. Struggling to find product market fit. | Moderate. Has found product market fit, trying to grow user base. | Stable product with wide user base. Have to roll out changes incrementally and run experiments. |
## Geographical location
| | US (Silicon Valley/NY) | Singapore |
| --- | --- | --- |
| Starting Pay | USD 100,000 | Monthly $4320 (Median), $5000 (75th percentile) |
| Talent Access | Global talent, diverse nationalities and backgrounds | Usually regional, mostly Asians |
| Types of Companies | HQ of large companies (Facebook, Amazon, Apple, Google, Microsoft, etc), Startups | Branch offices of large companies, Startups |
| Types of Engineering Work | Depends on size of office/company | Both product and infra (building new programming languages, frameworks, and tools) |

@ -0,0 +1,14 @@
---
id: mock-interviews
title: Mock Interviews
---
Interviewing is a skill that you can get better at. The steps mentioned above can be rehearsed over and over again until you have fully internalized them and following those steps become second nature to you. A good way to practice is to find a friend to partner with and the both of you can take turns to interview each other.
A great resource for practicing mock coding interviews would be [interviewing.io](https://iio.sh/r/DMCa). interviewing.io provides free, anonymous practice technical interviews with Google and Facebook engineers, which can lead to real jobs and internships. By virtue of being anonymous during the interview, the inclusive interview process is de-biased and low risk. At the end of the interview, both interviewer and interviewees can provide feedback to each other for the purpose of improvement. Doing well in your mock interviews will unlock the jobs page and allow candidates to book interviews (also anonymously) with top companies like Uber, Lyft, Quora, Asana and more. For those who are totally new to technical interviews, you can even view [recorded interviews](https://interviewing.io/recordings) and see how phone interviews are like. Read more about them [here](https://techcrunch.com/2017/09/27/interviewing-io-hopes-to-close-the-engineer-diversity-gap-with-anonymous-interviews/).
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 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.

@ -1,31 +1,33 @@
Negotiation
==
---
id: negotiation
title: Negotiation
---
### Ten Rules of Negotiation
## Ten Rules of Negotiation
Key points extracted from "Ten Rules for Negotiating a Job Offer" [Part 1](http://haseebq.com/my-ten-rules-for-negotiating-a-job-offer/) and [Part 2](https://haseebq.com/how-not-to-bomb-your-offer-negotiation/) by Haseeb Qureshi.
#### Get everything in writing
### Get everything in writing
Note down EVERYTHING on your phone call with the recruiters as they may be helpful later on. Even if there are things that are not directly monetary, if they relate to the job, write them down. If they tell you "we're working on porting the front-end to Angular," write that down. If they say they have 20 employees, write that down. You want as much information as you can. You'll forget a lot of this stuff, and it's going to be important in informing your final decision.
#### Always keep the door open
### Always keep the door open
Never give up your negotiating power until you're absolutely ready to make an informed, deliberate final decision. This means your job is to traverse as many of these decision points as possible without giving up the power to continue negotiating. Very frequently, your interlocutor will try to trick you into making a decision, or tie you to a decision you didn't commit to. You must keep verbally jiu-jitsu-ing out of these antics until you're actually ready to make your final decision.
#### Information is power
### Information is power
To protect your power in the negotiation, you must protect information as much as possible. A corollary of this rule is that you should not reveal to companies what you're currently making. So given this offer, don't ask for more money or equity or anything of the sort. Don't comment on any specific details of the offer except to clarify them. Companies will ask about your current compensation at different stages in the process—some before they ever interview you, some after they decide to make you an offer. But be mindful of this, and protect information.
> "Yeah, [COMPANY_NAME] sounds great! I really thought this was a good fit, and I'm glad that you guys agree. Right now I'm talking with a few other companies so I can't speak to the specific details of the offer until I'm done with the process and get closer to making a decision. But I'm sure we'll be able to find a package that we're both happy with, because I really would love to be a part of the team."
#### Always be positive
### Always be positive
Even if the offer is bad, it's extremely important to remain positive and excited about the company. This is because your excitement is one of your most valuable assets in a negotiation.
Despite whatever is happening in the negotiation, give the company the impression that 1) you still like the company, and that 2) you're still excited to work there, even if the numbers or the money or the timing is not working out. Generally the most convincing thing to signal this is to reiterate you love the mission, the team, or the problem they're working on, and really want to see things work out.
#### Don't be the decision maker
### Don't be the decision maker
Even if you don't particularly care what your friends/family/husband/mother thinks, by mentioning them, you're no longer the only person the recruiter needs to win over. There's no point in them trying to bully and intimidate you; the "true decision-maker" is beyond their reach. This is a classic technique in customer support and remediation. It's never the person on the phone's fault, they're just some poor schmuck doing their job. It's not their decision to make. This helps to defuse tension and give them more control of the situation.
@ -33,7 +35,7 @@ Even if you don't particularly care what your friends/family/husband/mother thin
It's much harder to pressure someone if they're not the final decision-maker. So take advantage of that.
#### Have alternatives
### Have alternatives
If you're already in the pipeline with other companies (which you should be if you're doing it right), you should proactively reach out and let them know that you've just received an offer. Try to build a sense of urgency. Regardless of whether you know the expiration date, all offers expire at some point, so take advantage of that.
@ -59,7 +61,7 @@ Have a strong BATNA (Best Alternative To a Negotiated Agreement) and communicate
> I'm also considering going back to grad school and getting a Master's degree in Postmodern Haberdashery. I'm excited about [YOUR COMPANY] though and would love to join the team, but the package has to make sense if I'm going to forego a life of ironic hatmaking.
#### Proclaim reasons for everything
### Proclaim reasons for everything
It's kind of a brain-hack, both for yourself and for your negotiating partner. Just stating a reason (any reason) makes your request feel human and important. It's not you being greedy, it's you trying to fulfill your goals.
@ -67,19 +69,19 @@ The more unobjectionable and sympathetic your reason, the better. If it's medica
Just go with it, state a reason for everything, and you'll find recruiters more willing to become your advocate.
#### Be motivated by more than just money
### Be motivated by more than just money
You should be motivated by money too of course, but it should be one among many dimensions you're optimizing for. How much training you get, what your first project will be, which team you join, or even who your mentor will be—these are all things you can and should negotiate.
Of course, to negotiate well you need to understand the other side's preferences. You want to make the deal better for both of you.
#### Understand what they value
### Understand what they value
Remember that you can always get salary raises as you continue to work at the company, but there's only one point at which you can get a signing bonus.
The easiest thing for a company to give though is stock (if the company offers stock). Companies like giving stock because it invests you in the company and aligns interests. It also shifts some of the risk from the company over to you and burns less cash.
#### Be winnable
### Be winnable
This is more than just giving the company the impression that you like them (which you continually should). But more so that you must give any company you're talking to a clear path on how to win you. Don't bullshit them or play stupid games. Be clear and unequivocal with your preferences and timeline.

@ -0,0 +1,26 @@
---
id: picking-a-language
title: Picking a Language
---
Before anything else, you need to pick a programming language to do your interviews in. Most companies will let you code in any language you want, the only exception I know being Google, where they only allow candidates to pick from Java, C++, JavaScript or Python for their algorithmic coding interviews.
## Some languages are more suited for interviews
There are some languages which are more suitable than others for coding interviews and some languages you absolutely want to avoid. From my experience as an interviewer, most candidates pick Python or Java. Other commonly seen languages include JavaScript, Ruby and C++. I would absolutely avoid lower level languages like C or Go, simply because they lack many standard library functions and data structures and some may require manual memory management.
Personally, Python is my de facto choice for algorithm coding interviews because it is succinct and has a pretty huge library of functions and data structures available. One of my top reasons for recommending Python is that it uses consistent APIs that operate on different data structures, such as `len()`, `for ... in ...` and slicing notation on sequences (strings/lists/tuples). Getting the last element in a sequence is `arr[-1]` and reversing it is simply `arr[::-1]`. You can achieve a lot with minimal syntax in Python.
Java is a decent choice too but having to constantly declare types in your code means extra keystrokes which results in slower coding/typing speed. This issue will be more apparent when you have to write on a whiteboard during on-site interviews. The reasons for choosing/not choosing C++ are similar to Java. Ultimately, Python, Java and C++ are decent choices of languages.
## Use a language you are familiar with
Most of the time, it is recommended that you use a language that you are extremely familiar with rather than picking up a new language just for doing interviews because the company uses that language heavily or just because you want to show that you are trendy.
If you are under time constraints, picking up a new language just for interviewing is hardly a good idea. Languages take time to master and if you are already spending most of your time and effort on mastering algorithms, there is barely spare effort left for mastering a new language. If you are familiar with using one of the mainstream languages, there isn't a strong reason to learn a new language just for interviewing.
If you have been using Java at work for a while now and do not have time to be comfortably familiar with another language, I would recommend just sticking to Java instead of picking up Python from scratch just for the sake of interviews. Doing so, you can avoid having to context switch between languages during work vs interviews. Most of the time, the bottleneck is in the thinking and not the writing. It takes some getting used to before one becomes fluent in a language and be able to wield it with ease.
## The exception to the norm
One exception to the convention of allowing you to "pick any programming language you want" is when you are interviewing for a domain-specific position, such as Front End/iOS/Android Engineer roles, in which you would need to be familiar with coding in JavaScript, Objective-C/Swift and Java respectively. If you need to use a data structure that the language does not support, such as a Queue or Heap in JavaScript, perhaps try asking the interviewer whether you can assume that you have a data structure that implements certain methods with specified time complexities. If the implementation of that data structure is not crucial to solving the problem, the interviewer will usually allow this. In reality, being aware of existing data structures and selecting the appropriate ones to tackle the problem at hand is more important than knowing the intricate implementation details.

@ -1,5 +1,7 @@
Psychological Tricks
==
---
id: psychological-tricks
title: Psychological Tricks
---
Here are some psychological tricks that will help you ace a job interview.

@ -1,5 +1,7 @@
Questions to Ask
==
---
id: questions-to-ask
title: Questions To Ask
---
Here are some good questions to ask at the end of the interview, extracted from various sources. The ones in **bold** are the ones that tend to make the interviewer go "That's a good question" and pause and think for a bit.
@ -38,6 +40,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?**
- **I do / don't have experience in domain X. How important is this for me to be able to succeed?**
- 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?
@ -48,8 +51,9 @@ 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?
- What resources does the company have for new hires to study its product and processes? Are there 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?
- How do you think my expertise would be relevant to this team? What unique value can I add?
### Product
@ -58,13 +62,15 @@ These questions are suitable for any technical role.
- 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)
- Is the team growing, and what sort of opportunities will there be in the next year/3 years?
- What are your highest priorities right now? For example, new features, new products, solidifying existing code, reducing operations overhead?
### Management
These questions are suitable for asking Engineering Managers, especially useful for the Team Matching phase of Google interviews or post-offer calls that your recruiters set up with the various team managers.
- **How do you train/ramp up engineers who are new to the team?**
- **What does success look like for your team?**
- **What does success look like for your team/project?**
- **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?**
@ -75,6 +81,18 @@ These questions are suitable for asking Engineering Managers, especially useful
- How often are 1:1s conducted?
- What is the current team composition like?
- What opportunities are available to switch roles? How does this work?
- Two senior team members disagree over a technical issue. How do you handle it?
- Have you managed a poor performer at some point in your career before? What did you do and how did it work?
- Where do you spend more of your time, high performers or low performers?
- Sometimes there's a trade-off between what's best for one of your team members and what's best for the team. Give an example of how you handled this and why.
- Give an example of a time you faced a difficult mentoring/coaching challenge. What did you do and why?
- What is your management philosophy?
- What is the role of data and metrics in managing a team like ours?
- What role does the manager play in making technical decisions?
- What is an example of a change you have made in the team that improved the team?
- What would be the most important problem you would want me to solve if I joined your team?
- What opportunities for growth will your team provide?
- What would I work on if I joined this team and who would I work most closely with?
### Leadership
@ -108,3 +126,5 @@ These questions are intended for senior level management, such as CEO, CTO, VPs.
- [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/)
- [What are good questions to ask during a software developer interview when asked "Do you have any questions now?"](https://www.quora.com/What-are-good-questions-to-ask-during-a-software-developer-interview-when-asked-do-you-have-any-questions-now/answer/John-L-Miller)
- [What are some good questions to ask when interviewing someone for a manager position?](https://www.quora.com/What-are-some-good-questions-to-ask-when-interviewing-someone-for-a-manager-position/answer/David-Seidman)

@ -1,20 +1,17 @@
Resume
==
---
id: resume
title: 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
## 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
### 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".
@ -26,23 +23,23 @@ 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
### 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.
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 their 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
## 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
### 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.
@ -51,7 +48,7 @@ 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
### 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.
@ -63,11 +60,11 @@ Information that a recruiter wants to know:
- Projects that you have worked on.
- Work experience/co-curricular activities.
- Skills/other interests.
- Street cred - GitHub/StackOverflow/LinkedIn profile (optional, but highly recommended).
- Street cred - GitHub/Stack Overflow/LinkedIn profile (optional, but highly recommended).
Information nobody needs to know:
- Your profile picture.
- Your profile picture. In the US, it is illegal to discriminate based on age, gender, race, or appearance.
- Address, home phone number, gender, religion, race, marital status, etc etc.
- Elementary, middle, high school.
- Your low GPA.
@ -78,7 +75,7 @@ Information nobody needs to know:
Ideally, keep it short, concise, but as detailed as possible.
#### 3. GPA does matter
### 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.**
@ -88,27 +85,27 @@ In a different scenario, some students have low GPA, but it might be due to some
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
### 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!!
Are you looking for a summer internship/full-time employment? What position are you applying for? Read the job description and know the job you are applying for!
**"Work experience" does not mean any work experience; it means *relevant* work experience.** If you are applying for a developer position, the recruiter is not interested to know that you were a student escort for girls walking back to their apartments at night, nor that you were a cashier at Starbucks. You would be better off writing about the project you did for some programming class - yes, even if it was just a school project. Tailor your experiences and projects according to the job you are applying for. Pick relevant details to emphasize on and do not be hesitant to drop stuff completely if they are totally irrelevant. Quality over quantity.
**"Work experience" does not mean any work experience; it means _relevant_ work experience.** If you are applying for a developer position, the recruiter is not interested to know that you were a student escort for girls walking back to their apartments at night, nor that you were a cashier at Starbucks. You would be better off writing about the project you did for some programming class - yes, even if it was just a school project. Tailor your experiences and projects according to the job you are applying for. Pick relevant details to emphasize on and do not be hesitant to drop stuff completely if they are totally irrelevant. Quality over quantity.
- Make sure the description is comprehensive. Avoid writing "Software engineering intern - write code". You are better off not writing anything.
- Based on my experience, most fresh grads do not have extremely relevant job experience (unless you are lucky to have scored a really rewarding internship). For developer positions, I think it is ok to not have any job experience and just list projects.
#### 5. Reverse chronological order
### 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
### 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
### 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
@ -122,20 +119,19 @@ Always list your resume in reverse chronological order - the most recent at the
- 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
### 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
### 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.
- 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
### 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.

@ -0,0 +1,96 @@
---
id: self-introduction
title: Self Introduction
---
Interviewers want to work with candidates they like. Leave a good/deep impression and it will increase your chances of success. Most of us are not strangers to self introductions as we meet new people now and then and have to introduce ourselves every once in a while. However, self introductions in interviews are slightly different from real life - you need to tweak it to your advantage - tailor the self introduction to the role and company you are applying for! Your self introduction evolves as you grow and are at a different stage of your life.
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 (or replace with other job-specific skills) a good fit for you? How is that applicable to our role or company goals?"
## The elevator pitch
An "elevator pitch" originates from a journalist trying to pitch an idea to an editor. The only time to catch the editor was in the elevator and she had only around 30 seconds to do so. The key elements of elevator pitches include:
- Short - You have limited time!
- Direct - As you only have limited time, you should get to the point
- Attention-grabbing - Present your most attractive ideas
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. Your self introduction is an elevator pitch for yourself!
Here are some tips to develop a good elevator pitch for yourself:
### Short basic background information
Include who you are, who you work for (or school and major), and what you do.
- For internships, you should mention the following: name, school and major, focus areas, past internships and/or noteworthy projects.
- For full-time roles, you should mention the following: name, past companies, noteworthy projects (best if it's a public consumer product that they might have heard of).
Does this look familiar? It is similar to your resume! Your resume is a condensed version of your knowledge and experiences and your self introduction is essentially a condensed version of your resume. As you grow older, professional experience becomes more important and school background becomes less important. Hence your self introduction changes as you become more senior.
### KISS (Keep It Simple and Sweet)
Tell them some highlights from your favorite/most impressive projects and including some numbers if they're impressive or challenges that you've overcome. 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_?
Tell the interviewer why you would make a good hire. Is your experience relevant to the company? Have you used a similar tech stack as the company or built relevant products? What unique talent(s) do you have that may give them confidence about your ability to contribute to the 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.
After coming up with your self introduction, keep it somewhere where you can refer/tweak in future Memorize them and in future you can just use it when you need to But dont sound like youre recalling it from your memory when youre actually saying it out. Sound natural!
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.
## Format
Prepare a self introduction that follows the following outline (inspired by "Cracking the Coding Interview" by Gayle McDowell):
1. A sentence about your current or most recent role.
1. A few sentences about your (academic) background. What did you focus on?
1. Some sentences about your professional experience after school/university. Where did you work? What projects did you deal with? What were the typical challenges and tasks? Which technologies did you use?
1. Finish with a statement saying why you are seeking a new job opportunity and why you are interested in the role you applied for.
## Examples
### Example 1: Front End Engineer at Facebook
#### Self introduction
> "Hi Im Yangshun and I graduated from National University of Singapore in 2015 with a degree in Computer Science. My interests are in Front End Engineering and I love to create beautiful performant products with delightful user experiences.
>
> Back in school, I designed and built a web application, NUSMods which solves a huge problem of class and timetable planning every semester. It receives over a million pageviews a month and is used by over 40,000 NUS students and even some professors. It is built using a modern web technology stack - React, Redux, Jest, Babel, Flow, webpack and is mobile-responsive."
>
> I'm interested in the Front End Engineer role at Facebook because I have been using Facebook Open Source Front End technologies for a while now and am inspired by Facebook's mission and Open Source culture.
#### Breakdown
- "I love to create beautiful performant products with delightful user experiences."
- Qualities that a Front End engineer should possess
- "It receives over a million pageviews a month and is used by over 30,000 NUS undergraduates and even some professors."
- Mention something about the project which stands out
- "It is built using a modern web technology stack - React, Redux, Jest, Babel, Flow, webpack and is mobile-responsive."
- Facebook tech stack! Also hints that you are familiar with modern web technologies
### Example 2: Front End Engineer at Lyft
#### Self introduction
> "Hi Im Yangshun and I graduated from National University of Singapore in 2015 with a degree in Computer Science. My interests are in Front End Engineering and I love to create beautiful performant products with delightful user experiences.
>
> I previously worked at Grab where I led the Grab for Work project. Grab for Work was a service for companies to make corporate transportation expenses convenient. Companies can create employee groups, set ride policies and share corporate payment methods with their employees. I built the project with another engineer over the period of 3 months on a React/Redux and Golang stack."
>
> I'm interested in the Front End Engineer role at Lyft because I like working in this ridesharing space and creating products for users to improve their life.
#### Breakdown
- "I love to create beautiful performant products with delightful user experiences."
- Same as above, qualities that a Front End engineer should possess.
- "I previously worked at Grab where I led the Grab for Work project."
- Lyft is Grab's sister company! In fact they even had a partnership in the past. Most Lyft engineers would have heard of Grab before and mentioning this catches their attention.
- "I built the project with another engineer over the period of 4 months on a React/Redux and Golang stack."
- Acknowledge that you work with others. Building a non-trivial system with just 2 people in 3 months is quite good for a non-trivial system. Lyft also uses Golang for their high performance systems.

@ -0,0 +1,47 @@
---
id: star-format
title: STAR Format
---
## What is STAR?
The [STAR](https://en.wikipedia.org/wiki/Situation,_task,_action,_result) format is a framework to help you organize your experience into sections that flows nicely. From Wikipedia:
- **Situation** - The interviewer wants you to present a recent challenge and situation which you found yourself in.
- **Task** - What were you required to achieve? The interviewer will be looking to see what you were trying to achieve from the situation. Some performance development methods use "Target" rather than "Task". Job interview candidates who describe a "Target" they set themselves instead of an externally imposed "Task" emphasize their own intrinsic motivation to perform and to develop their performance.
- **Action** - What did you do? The interviewer will be looking for information on what you did, why you did it and what the alternatives were.
- **Results** - What was the outcome of your actions? What did you achieve through your actions and did you meet your objectives? What did you learn from this experience and have you used this learning since?
## Example
Here's an example of how the STAR format can be used to answer the question: **"Tell me about a time in which you had a conflict and needed to influence somebody else"**.
#### Situation
> "I was the team lead of a school project about building a social network mobile web app. Our designer's mid-terms were approaching and didn't have time to produce the mockups. Our front end person was rushing him for the mockups so that he could proceed with his work and that was stressing the designer out. The atmosphere in the team was tense."
#### Task
> "As the team lead, I had to resolve the tension between the front end developer and the designer so that the team could work together peacefully and complete the project on time."
#### Action
> "I spoke to the front end developer to ask him why he was rushing the designer for the designs. He said that he wanted the designs early because it would be a waste of time rebuilding if the designer designed something different eventually. I explained to him that the mid-term dates were out of the designer's control and we had to be more understanding about each others' schedules.
>
> I spoke to the designer to get a rough idea of what he had in mind and asked him when he could commit to producing the high fidelity designs. He replied that he could start on them as soon as his mid-terms were over. I explained to him why the front end developer was pushing him for the mockups and that the front end developer had no ill intentions and simply wanted the project to succeed.
>
> As someone with some experience in UI/UX design, I came up with wireframe mocks, ran them by the designer for approval, then passed them to the front end developer to start building. I encouraged the front end developer to use placeholders and not be too concerned about the details for now. We could build the non-UI parts first (authentication, hook up with APIs) and tweak pixels and add polish later on. The front end developer agreed and went ahead with the approach. I explained to the front end developer that the designer will pass us the mockups after his mid-term, by &lt;DATE&gt;."
#### Result
> "When our designer ended mid-terms, he came back with beautiful mockups that fit well into the wireframes. Our front end developer implemented them with great care to detail. We ended up scoring top marks for the project and became a great team."
#### Qualities
Through the above, experienced interviewers can extract the following qualities from the mentioned behaviors.
- **Empathy** - Empathize with both roles and made sure to understand each individuals reasons
- **Willingness** - to wear multiple hats: Picked up the role of the designer and came up with wireframes
- **Project management** - Able to unblock the project by changing approaches midway to great effectiveness
- **Conflict management** - Explain to parties involved in conflict and make sure no hard feelings remain
- **Hold people accountable** - Get a confirmation date as to when the designer can produce the mockups and hold him accountable

@ -0,0 +1,40 @@
---
id: study-and-practice
title: Study and Practice
---
## Recap CS fundamentals
If you have been out of college for a while, it is highly advisable to review CS fundamentalsAlgorithms and Data Structures. Personally, I prefer to review as I practice, so I scan through my college notes and review the various algorithms as I work on algorithm problems from LeetCode and Cracking the Coding Interview.
This [interviews repository](https://github.com/kdn251/interviews) by Kevin Naughton Jr. served as a quick refresher for me.
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.
### Practice coding questions
Practice coding algorithms using your chosen language. While [Cracking the Coding Interview](http://www.crackingthecodinginterview.com/) is a good resource for practice, I prefer being able to type code, run it and get instant feedback. There are various Online Judges such as [LeetCode](https://leetcode.com/), [HackerRank](https://www.hackerrank.com/) and [CodeForces](http://codeforces.com/) for you to practice questions online and get used to the language. From experience, LeetCode questions are the most similar to the kind of questions being asked in interviews whereas HackerRank and CodeForces questions resemble competitive programming questions. If you practice enough LeetCode questions, there is a good chance that you would have seen/done your actual interview question (or some variant) on LeetCode before. If you are more of a visual person, [Coderust](https://www.educative.io/collection/5642554087309312/5679846214598656) explains the common algorithm questions through step-by-step visualizations which makes understanding the solutions much easier.
### Space/time complexities
Learn and understand the time and space complexities of the common operations in your chosen language. For Python, this [page](https://wiki.python.org/moin/TimeComplexity) will come in handy. Also find out the underlying sorting algorithm that is being used in the language's `sort()` function and its time and space complexity (in Python its Timsort which is a hybrid sort). After completing a question on LeetCode, I usually add the time and space complexities of the written code as comments above the function body to remind myself to analyze the algorithm after I am done with the implementation.
### Practice good coding style
Read up on the recommended coding style for your language and stick to it. If you have chosen Python, refer to the PEP 8 Style Guide. If you have chosen Java, refer to Google's Java Style Guide.
### Internalize the pitfalls
Find out and be familiar with the common pitfalls and caveats of the language. If you point them out during the interview and intelligently avoid falling into them, you will usually impress the interviewer and that results in bonus points for your feedback, regardless of whether the interviewer is familiar with the language or not.
### Broaden exposure
Gain a broad exposure to questions from various topics. In the second half of the article I mention algorithm topics and practice questions for each topic. Do around 100200 LeetCode questions and you should be good.
Practice, practice and more practice!

@ -0,0 +1,76 @@
---
id: understanding-compensation
title: Understanding Compensation
---
Compensation is a huge factor when it comes to deciding between job offers. This section gives you a breakdown of the common components of compensation in the tech industry.
In most companies, your compensation will consist of base salary, a performance bonus and equity/stocks. For compensation data, check out [Levels.fyi](https://www.levels.fyi).
### Base salary
Base salary is a fixed amount of salary you get for showing up at work and is unaffected by how well the company is performing or the industry is doing. It is the only non-variable component of your compensation.
Fresh graduates in the Bay Area can usually expect to get a base salary of above USD 100,000 (before taxes). The salary for fresh graduates at Facebook/Google is known to be in the USD 100,000 - 150,000 range.
Startups usually offer a bit higher for fresh graduate (USD 120,000 - 130,000) to make up for the lack of liquidity of the equity grant (not yet real cash).
Base salary doesn't increase linearly as you become more senior; it will plateau off eventually. As employees become increasingly senior within the company, the higher the proportion of their compensation comes from company-dependent factors such as bonus and equity. This is because senior employees are expected to influence the people around them and drive the company forward. A senior employee's performance will be based on how well the company does as a whole; the individual factor will not be as much.
There are some exceptions to the system. Companies like Netflix pay top in the industry (sometimes even more than Facebook/Google) and give employees the option to receive their entire compensation as base salary, that is, to convert the equity component into their base. For the risk-adverse, this is a great choice.
### Bonus
Bonuses are usually paid on a semi-annual basis and are typically dependent on a few factors - level of seniority, individual performance in that time period, company performance in that time period.
- **Level of seniority** - This is usually a multiplier of the base salary, and the multiplier increases as the employee moves up the ranks
- **Individual performance** - This is a multiplier of how well an employee performed in that time period. E.g. meeting expectations results in a 100% multiplier and exceeding expectations results in a >100% multiplier. Companies like Facebook and Apple reward their top performers handsomely, and the multiplier can go up to 300% for the extremely high-performing employees
- **Company performance** - How well the company is doing. This multiplier will be the same for all employees
#### Examples
- Bob is a Software Engineer fresh out of college. His base salary is 100,000, is a fresh grad (seniority multiplier: 10%), crushed expectations for the half (individual performance multiplier: 200%) and his company did pretty well (company performance multiplier: 120%). For that half, his bonus will be as follows:
- **Bonus:** 100,000 x 50% (half a year) x 10% (seniority) x 200% (individual performance) x 120% (company performance) = 12000
- Alice is an Engineering Manager with 10 years of professional experience. Her base salary is 220,000, is an experienced engineering manager (seniority multiplier: 20%), exceeded expectations for the half (individual performance multiplier: 150%) and her company did pretty awesome (company performance multiplier: 130%). For that half, her bonus will be as follows:
- **Bonus:** 220,000 x 50% (half a year) x 20% (seniority) x 150% (individual performance) x 130% (company performance) = 42900
Hence the amount of bonus you receive can be highly variable and senior employees get a higher proportion of their compensation from bonuses.
### Equity/Stocks
Equity is what differentiates a tech job from a non-tech one. Equity means a share of the company; this signifies ownership and motivates employees to work in the best interests of the company. They can be a significant portion of one's compensation, sometimes even more than the base salary, especially for senior employees.
Equity usually vests (becomes available to you) over a period of time (typically 4 years) and can vest equally every month/quarter/year. A vesting cliff means the minimum period of time before your vesting begins. For example, if you are granted 4,800 shares over a 4 year schedule with a 1 year cliff, and monthly vesting, you will get 1,200 shares at the end of your first year and 100 shares every month thereafter for the subsequent 3 years.
Until the company goes public or gets acquired, the equity is not worth anything. Be mindful of what you are getting yourself into!
Not all equity is treated equally. Depending on the company you join and which stage that company is at, you may receive one of the following types: stock options or stock grants.
#### Stock options
Stock options are typically given by mid-stage companies. Stock options are different from stocks, which represents the immediate ownership of a company! Stock options are the **option/right** to purchase stocks at a given strike price, hence it's not free. However, the cost of each stock is usually quite low and fixed at a strike price, which is equal to the fair market value of the stock when it was granted to you. You are guaranteed to be able to purchase the stock at that price regardless of future increases.
When you leave a company, there is an exercise window (deadline given for you to exercise your options before they are gone), so it is important to have enough liquid cash to purchase them when planning a departure.
#### Stock grants
A stock grant is commonly referred to as a Restricted Stock Unit (RSU) and it means you possess the stock immediately. If the company is public, you can sell them during defined trading windows.
More reading on the topic can be done [here](https://gist.github.com/yossorion/4965df74fd6da6cdc280ec57e83a202d).
### Signing bonus
This is a one-time lump sum that is paid to you when you join a company. This amount is typically in the range of USD 10,000 to USD 20,000 but can even go up to USD 50,000 (Google) and USD 100,000 (Facebook).
There can be conditions attached to signing bonuses, such as having to return a pro-rated amount if an employee leaves before the one-year mark. Make sure you are aware of them before you sign the offer.
### Misc bonuses/perks
While these perks are not exactly cash, they can help you save money which is almost equivalent to getting compensated more.
- Free meals - Food is not exactly cheap in the Bay Area and having some meals provided on weekdays can result in saving few thousand dollars a year
- Relocation bonus - Helpful if you are moving from abroad, and this can partially offset costs due to relocating
- Shuttle service - Public transportation in the Bay Area is not that great and the most common form of commute is driving. Being able to take a shuttle service helps in saving money on gas, transport, and freeing up your mind to do other things during the commute

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

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

@ -1,5 +1,4 @@
Collaborative Document Editor
==
# Collaborative Document Editor
## Variants

@ -1,5 +1,4 @@
News Feed
==
# News Feed
## Variants
@ -68,6 +67,7 @@ TODO
> A common optimization is to store feed content together with feedID in user-feed table so that we don't need to join the feed table any more. This approach is called denormalization, which means by adding redundant data, we can optimize the read performance (reducing the number of joins).
>
> The disadvantages are obvious:
>
> - Data redundancy. We are storing redundant data, which occupies storage space (classic time-space trade-off).
> - Data consistency. Whenever we update a feed, we need to update both feed table and user-feed table. Otherwise, there is data inconsistency. This increases the complexity of the system.
> - Remember that there's no one approach always better than the other (normalization vs denormalization). It's a matter of whether you want to optimize for read or write.
@ -76,9 +76,9 @@ TODO
- The most straightforward way is to fetch posts from all the people you follow and render them sorted by time.
- There can be many posts to fetch. How many posts should you fetch?
- What are the pagination approaches and the pros and cons of each approach?
- Offset by page size
- Offset by time
- What are the pagination approaches and the pros and cons of each approach?
- Offset by page size
- Offset by time
- What data should the post contain when you initially fetch them?
- Lazy loading approach for loading associated data: media, comments, people who liked the post.
- Media

@ -1,5 +1,4 @@
Search Engine
==
# Search Engine
###### References

@ -1,5 +1,4 @@
Databases
==
# Databases
## General

@ -1,5 +1,4 @@
Networking
==
# Networking
- Given an IPv4 IP address p and an integer n, return a list of CIDR strings that most succinctly represents the range of IP addresses from p to (p + n).
- Describe what happens when you enter a url in the web browser.

@ -1,11 +1,10 @@
Security
==
# Security
## Encryption
#### Symmetrical Encryption
- Symmetrical encryption is a type of encryption where one key can be used to encrypt messages and also decrypt the same message.
- Symmetrical encryption is a type of encryption where the same key is used to encrypt plaintext messages and to decrypt ciphertext.
- Symmetrical encryption is usually much less computationally expensive as compared to asymmetric encryption.
- Often called "shared secret" encryption, or "secret key" encryption.
- To use a symmetric encryption scheme, the sender and receiver must securely share a key in advance. This sharing can be done via asymmetric encryption.
@ -13,8 +12,8 @@ Security
#### Asymmetric Encryption
- A pair of keys are required: a **private key** and a **public key**. Public keys can be shared with anyone while private keys should be kept secret and known only to the owner.
- A private key can be used to decrypt a message encrypted by a public key. A successful decryption verifies that the holder possesses the private key.
- Also known as public key cryptography.
- A private key can be used to decrypt a message encrypted by the corresponding public key. A successful decryption verifies that the holder possesses the private key.
- Also known as public-key cryptography.
## Public Key Infrastructure
@ -30,7 +29,7 @@ An SSH session consists of two stages, **Negotiating Encryption** and **User Aut
#### Negotiating Encryption
The goal of this stage is for the client and server to agree upon and establish encryption to protect future communication, by generating an identical session key. One possible algorithm to generate the key is the DiffieHellman key exchange scheme. Each party generates a public/private key pair and exchanges the public key. After obtaining an authentic copy of each other's public keys, each party can compute a shared secret offline.
The goal of this stage is for the client and server to agree upon and establish encryption to protect future communication, by generating an identical session key. One possible algorithm to generate the session key is the DiffieHellman key exchange scheme. Each party generates a public/private key pair and exchanges the public key. After obtaining an authentic copy of each other's public keys, each party can compute a shared secret offline.
The basis of this procedure for classic Diffie-Hellman is:

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

@ -1,5 +1,4 @@
Software Engineering
==
# Software Engineering
## What is the difference between an interface and abstract class?

@ -0,0 +1,3 @@
# Front-end Job Interview Questions
Front-end Job Interview Questions have been migrated [here](https://github.com/yangshun/front-end-interview-handbook).

@ -1,9 +1,8 @@
Basics
==
# Basics
## Disclaimer
These items will all change based on your specific company and needs but these items area starting point.
All these items will change based on your specific company and needs but these items area are the starting point.
## Items To Consider
@ -11,10 +10,9 @@ These items will all change based on your specific company and needs but these i
- **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 __?")
- **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?
- **Nitpicking** - Sometimes pseudocode 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 code. Give some subtle hints like "I see you're doing \_\_\_\_, can you think of any other ways to accomplish this?" It's unlikely that the interviewee will be working in a silo should they get the job, is there any reason they should be during the interview?

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

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

@ -0,0 +1,43 @@
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 &&
val2 !== 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;

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

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

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

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

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

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

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

@ -0,0 +1,30 @@
function traverse(matrix) {
const DIRECTIONS = [[0, 1], [0, -1], [1, 0], [-1, 0]];
const rows = matrix.length;
const 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,62 @@
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,
]),
);

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

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

@ -66,4 +66,3 @@ print(bisect_right([1, 2, 3, 3, 10], 10) == 5)
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,45 @@
def graph_dfs(matrix):
rows, cols = len(matrix), len(matrix[0])
visited = set()
directions = ((0, 1), (0, -1), (1, 0), (-1, 0))
def dfs(i, j):
if (i, j) in visited:
return
visited.add((i, j))
# Traverse neighbors.
for direction in directions:
next_i, next_j = i + direction[0], j + direction[1]
if 0 <= next_i < rows and 0 <= next_j < cols: # Check boundary.
# Add any other checking here ^
dfs(next_i, next_j)
for i in range(rows):
for j in range(cols):
dfs(i, j)
# Follow up:
# 1) Diagonal cells are considered neighbors
# 2) View the matrix like Earth, right boundary is adjacent to the left boundary, top adjacent to left, etc.
def graph_dfs_diagonals_and_boundary_wrap(matrix):
rows, cols = len(matrix), len(matrix[0])
visited = set()
# Change 1: Add 4 more diagonal directions.
directions = ((0, 1), (0, -1), (1, 0), (-1, 0), (-1, -1), (1, 1), (1, -1), (-1, 1))
def dfs(i, j):
if (i, j) in visited:
return
visited.add((i, j))
for direction in directions:
# Change 2: No more boundary, use modulo to allow traversal that exceed boundaries to wrap around.
next_i, next_j = (i + direction[0] + rows) % rows, (j + direction[1] + cols) % cols
dfs(next_i, next_j)
for i in range(rows):
for j in range(cols):
dfs(i, j)
graph_dfs([
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
])

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save