Top 10 Algorithms for Coding Interview--reference
Update History:
Web Version latest update: 4/6/2014
PDF Version latest update: 1/16/2014
The following are top 10 algorithms related topics for coding interviews. As understanding those concepts requires much more effort, this list below only serves as an introduction. They are viewed from a Java perspective and the following topics will be covered: String/Array/Matrix, Linked List, Tree, Heap, Graph, Sorting, Recursion vs. Iteration, Dynamic Programming, Bit Manipulation, Probability, Combinations and Permutations, and other problems that need us to find patterns.
1. String/Array/Matrix
First of all, String in Java is a class that contains a char array and other fields and methods. Without code auto-completion of any IDE, the following methods should be remembered.
toCharArray() //get char array of a String |
Strings/arrays are easy to understand, but questions related to them often require advanced algorithm to solve, such as dynamic programming, recursion, etc.
Classic problems:
1) Evaluate Reverse Polish Notation
2) Longest Palindromic Substring
3) Word Break
4) Word Ladder
5) Median of Two Sorted Arrays
6) Regular Expression Matching
7) Merge Intervals
8) Insert Interval
9) Two Sum
9) 3Sum
9) 4Sum
10) 3Sum Closest
11) String to Integer
12) Merge Sorted Array
13) Valid Parentheses
14) Implement strStr()
15) Set Matrix Zeroes
16) Search Insert Position
17) Longest Consecutive Sequence
18) Valid Palindrome
19) Spiral Matrix
20) Search a 2D Matrix
21) Rotate Image
22) Triangle
23) Distinct Subsequences Total
24) Maximum Subarray
25) Remove Duplicates from Sorted Array
26) Remove Duplicates from Sorted Array II
27) Longest Substring Without Repeating Characters
28) Longest Substring that contains 2 unique characters
29) Palindrome Partitioning
2. Linked List
The implementation of a linked list is pretty simple in Java. Each node has a value and a link to next node.
class Node {
|
Two popular applications of linked list are stack and queue.
Stack
class Stack{
|
Queue
class Queue{
|
It is worth to mention that Java standard library already contains a class called “Stack“, and LinkedListcan be used as a Queue (add() and remove()). (LinkedList implements the Queue interface) If you need a stack or queue to solve problems during your interview, you can directly use them.
Classic Problems:
1) Add Two Numbers
2) Reorder List
3) Linked List Cycle
4) Copy List with Random Pointer
5) Merge Two Sorted Lists
6) Merge k Sorted Lists *
7) Remove Duplicates from Sorted List
8) Partition List
9) LRU Cache
3. Tree & Heap
Tree here is normally binary tree. Each node contains a left node and right node like the following:
class TreeNode{
|
Here are some concepts related with trees:
- Binary Search Tree: for all nodes, left children <= current node <= right children
- Balanced vs. Unbalanced: In a balanced tree, the depth of the left and right subtrees of every node differ by 1 or less.
- Full Binary Tree: every node other than the leaves has two children.
- Perfect Binary Tree: a full binary tree in which all leaves are at the same depth or same level, and in which every parent has two children.
- Complete Binary Tree: a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible
Heap is a specialized tree-based data structure that satisfies the heap property. The time complexity of its operations are important (e.g., find-min, delete-min, insert, etc). In Java, PriorityQueue is important to know.
Classic problems:
1) Binary Tree Preorder Traversal
2) Binary Tree Inorder Traversal
3) Binary Tree Postorder Traversal
4) Word Ladder
5) Validate Binary Search Tree
6) Flatten Binary Tree to Linked List
7) Path Sum
8) Construct Binary Tree from Inorder and Postorder Traversal
9) Convert Sorted Array to Binary Search Tree
10) Convert Sorted List to Binary Search Tree
11) Minimum Depth of Binary Tree
12) Binary Tree Maximum Path Sum *
13) Balanced Binary Tree
4. Graph
Graph related questions mainly focus on depth first search and breath first search. Depth first search is straightforward, you can just loop through neighbors starting from the root node.
Below is a simple implementation of a graph and breath first search. The key is using a queue to store nodes.

1) Define a GraphNode
class GraphNode{
|
2) Define a Queue
class Queue{
|
3) Breath First Search uses a Queue
public class GraphTest {
|
Output:
value: 4
Classic Problems:
1) Clone Graph
5. Sorting
Time complexity of different sorting algorithms. You can go to wiki to see basic idea of them.
| Algorithm | Average Time | Worst Time | Space |
| Bubble sort | n^2 | n^2 | 1 |
| Selection sort | n^2 | n^2 | 1 |
| Insertion sort | n^2 | n^2 | |
| Quick sort | n log(n) | n^2 | |
| Merge sort | n log(n) | n log(n) | depends |
* BinSort, Radix Sort and CountSort use different set of assumptions than the rest, and so they are not “general” sorting methods. (Thanks to Fidel for pointing this out)
Here are some implementations/demos, and in addition, you may want to check out how Java developers sort in practice.
1) Mergesort
2) Quicksort
3) InsertionSort.
6. Recursion vs. Iteration
Recursion should be a built-in thought for programmers. It can be demonstrated by a simple example.
Question:
there are n stairs, each time one can climb 1 or 2. How many different ways to climb the stairs?
Step 1: Finding the relationship before n and n-1.
To get n, there are only two ways, one 1-stair from n-1 or 2-stairs from n-2. If f(n) is the number of ways to climb to n, then f(n) = f(n-1) + f(n-2)
Step 2: Make sure the start condition is correct.
f(0) = 0;
f(1) = 1;
public static int f(int n){
|
The time complexity of the recursive method is exponential to n. There are a lot of redundant computations.
f(4) + f(3)
f(3) + f(2) + f(2) + f(1)
f(2) + f(1) + f(2) + f(2) + f(1)
It should be straightforward to convert the recursion to iteration.
public static int f(int n) {
|
For this example, iteration takes less time. You may also want to check out Recursion vs Iteration.
7. Dynamic Programming
Dynamic programming is a technique for solving problems with the following properties:
- An instance is solved using the solutions for smaller instances.
- The solution for a smaller instance might be needed multiple times.
- The solutions to smaller instances are stored in a table, so that each smaller instance is solved only once.
- Additional space is used to save time.
The problem of climbing steps perfectly fit those 4 properties. Therefore, it can be solve by using dynamic programming.
public static int[] A = new int[100]; |
Classic problems:
1) Edit Distance
2) Longest Palindromic Substring
3) Word Break
4) Maximum Subarray
8. Bit Manipulation
Bit operators:
| OR (|) | AND (&) | XOR (^) | Left Shift (<<) | Right Shift (>>) | Not (~) |
| 1|0=1 | 1&0=0 | 1^0=1 | 0010<<2=1000 | 1100>>2=0011 | ~1=0 |
Get bit i for a give number n. (i count from 0 and starts from right)
public static boolean getBit(int num, int i){
|
For example, get second bit of number 10.
1<<1= 10
1010&10=10
10 is not 0, so return true;
Classic Problems:
1) Find Single Number
2) Maximum Binary Gap
9. Probability
Solving probability related questions normally requires formatting the problem well. Here is just a simple example of such kind of problems.
There are 50 people in a room, what’s the probability that two people have the same birthday? (Ignoring the fact of leap year, i.e., 365 day every year)
Very often calculating probability of something can be converted to calculate the opposite. In this example, we can calculate the probability that all people have unique birthdays. That is: 365/365 * 364/365 * 363/365 * … * 365-n/365 * … * 365-49/365. And the probability that at least two people have the same birthday would be 1 – this value.
public static double caculateProbability(int n){
|
calculateProbability(50) = 0.97
10. Combinations and Permutations
The difference between combination and permutation is whether order matters.
Example 1:
Given 5 numbers – 1, 2, 3, 4 and 5, print out different sequence of the 5 numbers. 4 can not be the third one, 3 and 5 can not be adjacent. How many different combinations?
Example 2:
Given 5 banaba, 4 pear, and 3 apple, assuming one kind of fruit are the same, how many different combinations?
Class Problems:
1) Permutations
2) Permutations II
3) Permutation Sequence
11. Others
Other problems need us to use observations to form rules to solve them.
Classic problems:
1) Reverse Integer
2) Palindrome Number
3) Pow(x,n)
4) Subsets
5) Subsets II
References/Recommended Materials:
1. Binary tree
2. Introduction to Dynamic Programming
3. UTSA Dynamic Programming slides
4. Birthday paradox
5. Cracking the Coding Interview: 150 Programming InterviewQuestions and Solutions, Gayle Laakmann McDowell
6. Counting sort
7. LeetCode Online Judge
reference:http://www.programcreek.com/2012/11/top-10-algorithms-for-coding-interview/
Top 10 Algorithms for Coding Interview--reference的更多相关文章
- 转:Top 10 Algorithms for Coding Interview
The following are top 10 algorithms related concepts in coding interview. I will try to illustrate t ...
- Top 10 Algorithms of 20th and 21st Century
Top 10 Algorithms of 20th and 21st Century MATH 595 (Section TTA) Fall 2014 TR 2:00 pm - 3:20 pm, Ro ...
- 18 Candidates for the Top 10 Algorithms in Data Mining
Classification============== #1. C4.5 Quinlan, J. R. 1993. C4.5: Programs for Machine Learning.Morga ...
- Favorites of top 10 rules for success
Dec. 31, 2015 Stayed up to last minute of 2015, 12:00am, watching a few of videos about top 10 rules ...
- Cracking the Coding Interview(Stacks and Queues)
Cracking the Coding Interview(Stacks and Queues) 1.Describe how you could use a single array to impl ...
- crack the coding interview
crack the coding interview answer c++ 1.1 #ifndef __Question_1_1_h__ #define __Question_1_1_h__ #i ...
- TOP 10 ONLINE COMPILER
Top 10 Online Compilers +1338 Tweet Share106 Share Pin 444 Shares Online compilers are one type of t ...
- whiteboard & coding interview practice
whiteboard & coding interview practice 白板 & 面试 & 编码练习 Algorithm https://www.freecodecamp ...
- Top 10 Methods for Java Arrays
作者:X Wang 出处:http://www.programcreek.com/2013/09/top-10-methods-for-java-arrays/ 转载文章,转载请注明作者和出处 The ...
随机推荐
- CF 55D - Beautiful numbers(数位DP)
题意: 如果一个数能被自己各个位的数字整除,那么它就叫 Beautiful numbers.求区间 [a,b] 中 Beautiful numbers 的个数. 分析:先分析出,2~9 的最大的最小公 ...
- mac中viso的兼容工具
http://www.orsoon.com/Mac/77738.html破解教程 http://www.pc6.com/mac/111747.html下载地址 很强大,很爽.
- uva 11468 Substring
题意:给你 k 个模板串,然后给你一些字符的出现概率,然后给你一个长度 l ,问你这些字符组成的长度为 l 的字符串不包含任何一个模板串的概率. 思路:AC自动机+概论DP 首先用K个模板构造好AC自 ...
- uva 10652
大意:有n块矩形木板,你的任务是用一个面积尽量小的凸多边形把它们包起来,并计算出木板站整个包装面积的百分比. 思路:按照题意将所有矩形顶点坐标存起来,旋转时先旋转从中心出发的向量,求得各个坐标之后,求 ...
- BNUOJ-29364 Bread Sorting 水题
题目链接:http://www.bnuoj.com/bnuoj/problem_show.php?pid=29364 题意:给一个序列,输出序列中,二进制1的个数最少的数.. 随便搞搞就行了,关于更多 ...
- HDU-4664 Triangulation 博弈,SG函数找规律
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4664 题意:一个平面上有n个点(一个凸多边形的顶点),每次可以连接一个平面上的两个点(不能和已经连接的 ...
- hdoj 2829 Lawrence 四边形不等式优化dp
dp[i][j]表示前i个,炸j条路,并且最后一个炸在i的后面时,一到i这一段的最小价值. dp[i][j]=min(dp[i][k]+w[k+1][i]) w[i][j]表示i到j这一段的价值. # ...
- webServices
引用项目的配置文件: <system.serviceModel> <bindings> <basicHttpBinding> <!--旅游供应--> & ...
- 查看mysql的注册表路径
原文地址:http://www.cppblog.com/lanshengsheng/archive/2012/11/23/195592.html
- SQL Server 2005 盛宴系列 经典教程
SQL Server 2005 盛宴系列 经典教程 [复制链接] 发表于 2007-3-27 14:08 | 来自 51CTO网页 [只看他] 楼主 TECHNET SQL serve ...