By X Wang

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.

  1. toCharArray() //get char array of a String
  2. Arrays.sort() //sort an array
  3. Arrays.toString(char[] a) //convert to string
  4. charAt(int x) //get a char at the specific index
  5. length() //string length
  6. length //array size
  7. substring(int beginIndex)
  8. substring(int beginIndex, int endIndex)
  9. Integer.valueOf()//string to integer
  10. String.valueOf()/integer to 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.

  1. class Node {
  2. int val;
  3. Node next;
  4.  
  5. Node(int x) {
  6. val = x;
  7. next = null;
  8. }
  9. }

Two popular applications of linked list are stack and queue.

Stack

  1. class Stack{
  2. Node top;
  3.  
  4. public Node peek(){
  5. if(top != null){
  6. return top;
  7. }
  8.  
  9. return null;
  10. }
  11.  
  12. public Node pop(){
  13. if(top == null){
  14. return null;
  15. }else{
  16. Node temp = new Node(top.val);
  17. top = top.next;
  18. return temp;
  19. }
  20. }
  21.  
  22. public void push(Node n){
  23. if(n != null){
  24. n.next = top;
  25. top = n;
  26. }
  27. }
  28. }

Queue

  1. class Queue{
  2. Node first, last;
  3.  
  4. public void enqueue(Node n){
  5. if(first == null){
  6. first = n;
  7. last = first;
  8. }else{
  9. last.next = n;
  10. last = n;
  11. }
  12. }
  13.  
  14. public Node dequeue(){
  15. if(first == null){
  16. return null;
  17. }else{
  18. Node temp = new Node(first.val);
  19. first = first.next;
  20. return temp;
  21. }
  22. }
  23. }

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:

  1. class TreeNode{
  2. int value;
  3. TreeNode left;
  4. TreeNode right;
  5. }

Here are some concepts related with trees:

  1. Binary Search Tree: for all nodes, left children <= current node <= right children
  2. Balanced vs. Unbalanced: In a balanced tree, the depth of the left and right subtrees of every node differ by 1 or less.
  3. Full Binary Tree: every node other than the leaves has two children.
  4. 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.
  5. 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

  1. class GraphNode{
  2. int val;
  3. GraphNode next;
  4. GraphNode[] neighbors;
  5. boolean visited;
  6.  
  7. GraphNode(int x) {
  8. val = x;
  9. }
  10.  
  11. GraphNode(int x, GraphNode[] n){
  12. val = x;
  13. neighbors = n;
  14. }
  15.  
  16. public String toString(){
  17. return "value: "+ this.val;
  18. }
  19. }

2) Define a Queue

  1. class Queue{
  2. GraphNode first, last;
  3.  
  4. public void enqueue(GraphNode n){
  5. if(first == null){
  6. first = n;
  7. last = first;
  8. }else{
  9. last.next = n;
  10. last = n;
  11. }
  12. }
  13.  
  14. public GraphNode dequeue(){
  15. if(first == null){
  16. return null;
  17. }else{
  18. GraphNode temp = new GraphNode(first.val, first.neighbors);
  19. first = first.next;
  20. return temp;
  21. }
  22. }
  23. }

3) Breath First Search uses a Queue

  1. public class GraphTest {
  2.  
  3. public static void main(String[] args) {
  4. GraphNode n1 = new GraphNode(1);
  5. GraphNode n2 = new GraphNode(2);
  6. GraphNode n3 = new GraphNode(3);
  7. GraphNode n4 = new GraphNode(4);
  8. GraphNode n5 = new GraphNode(5);
  9.  
  10. n1.neighbors = new GraphNode[]{n2,n3,n5};
  11. n2.neighbors = new GraphNode[]{n1,n4};
  12. n3.neighbors = new GraphNode[]{n1,n4,n5};
  13. n4.neighbors = new GraphNode[]{n2,n3,n5};
  14. n5.neighbors = new GraphNode[]{n1,n3,n4};
  15.  
  16. breathFirstSearch(n1, 5);
  17. }
  18.  
  19. public static void breathFirstSearch(GraphNode root, int x){
  20. if(root.val == x)
  21. System.out.println("find in root");
  22.  
  23. Queue queue = new Queue();
  24. root.visited = true;
  25. queue.enqueue(root);
  26.  
  27. while(queue.first != null){
  28. GraphNode c = (GraphNode) queue.dequeue();
  29. for(GraphNode n: c.neighbors){
  30.  
  31. if(!n.visited){
  32. System.out.print(n + " ");
  33. n.visited = true;
  34. if(n.val == x)
  35. System.out.println("Find "+n);
  36. queue.enqueue(n);
  37. }
  38. }
  39. }
  40. }
  41. }

Output:

value: 2 value: 3 value: 5 Find value: 5
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;

  1. public static int f(int n){
  2. if(n <= 2) return n;
  3. int x = f(n-1) + f(n-2);
  4. return x;
  5. }

The time complexity of the recursive method is exponential to n. There are a lot of redundant computations.

f(5)
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.

  1. public static int f(int n) {
  2.  
  3. if (n <= 2){
  4. return n;
  5. }
  6.  
  7. int first = 1, second = 2;
  8. int third = 0;
  9.  
  10. for (int i = 3; i <= n; i++) {
  11. third = first + second;
  12. first = second;
  13. second = third;
  14. }
  15.  
  16. return third;
  17. }

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:

  1. An instance is solved using the solutions for smaller instances.
  2. The solution for a smaller instance might be needed multiple times.
  3. The solutions to smaller instances are stored in a table, so that each smaller instance is solved only once.
  4. 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.

  1. public static int[] A = new int[100];
  2.  
  3. public static int f3(int n) {
  4. if (n <= 2)
  5. A[n]= n;
  6.  
  7. if(A[n] > 0)
  8. return A[n];
  9. else
  10. A[n] = f3(n-1) + f3(n-2);//store results so only calculate once!
  11. return A[n];
  12. }

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)

  1. public static boolean getBit(int num, int i){
  2. int result = num & (1<<i);
  3.  
  4. if(result == 0){
  5. return false;
  6. }else{
  7. return true;
  8. }
  9. }

For example, get second bit of number 10.

i=1, n=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.

  1. public static double caculateProbability(int n){
  2. double x = 1;
  3.  
  4. for(int i=0; i<n; i++){
  5. x *= (365.0-i)/365.0;
  6. }
  7.  
  8. double pro = Math.round((1-x) * 100);
  9. return pro/100;
  10. }

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的更多相关文章

  1. 转:Top 10 Algorithms for Coding Interview

    The following are top 10 algorithms related concepts in coding interview. I will try to illustrate t ...

  2. 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 ...

  3. 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 ...

  4. 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 ...

  5. 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 ...

  6. crack the coding interview

    crack the coding interview answer c++ 1.1 #ifndef __Question_1_1_h__  #define __Question_1_1_h__  #i ...

  7. TOP 10 ONLINE COMPILER

    Top 10 Online Compilers +1338 Tweet Share106 Share Pin 444 Shares Online compilers are one type of t ...

  8. whiteboard & coding interview practice

    whiteboard & coding interview practice 白板 & 面试 & 编码练习 Algorithm https://www.freecodecamp ...

  9. Top 10 Methods for Java Arrays

    作者:X Wang 出处:http://www.programcreek.com/2013/09/top-10-methods-for-java-arrays/ 转载文章,转载请注明作者和出处 The ...

随机推荐

  1. 临时禁用Resharper

    Visual Studio 菜单 –> 工具 –> 选项 –> ReSharper –> Suspend按钮

  2. jQuery遍历DOM

    jQuery提供了多种遍历DOM的方法.遍历方法中最大的种类是树遍历. 向上遍历DOM树 parent():返回被选元素的直接父元素 parents():返回被选元素的所有祖先元素,它一直遍历到根元素 ...

  3. 序列化类型为XX的对象时检测到循环引用

    /// 产品列表展示 /// </summary> /// <returns></returns> ) { //获得所有组别 Galasys_IBLL.IT_BIZ ...

  4. ZOJ 3469 Food Delivery 区间DP

    这道题我不会,看了网上的题解才会的,涨了姿势,现阶段还是感觉区间DP比较难,主要是太弱...QAQ 思路中其实有贪心的意思,n个住户加一个商店,分布在一维直线上,应该是从商店开始,先向两边距离近的送, ...

  5. 【原】Redis-LRU缓存

    Redis高级篇 Redis-LRU缓存 将Redis作为缓存使用时,有时添加新数据时,旧数据是很难被清空的. LRU(Least Recently Used) 近期最少使用算法是常用算法之一. 最大 ...

  6. js基础第八天

    返回前面起第一个字符位置 indexOf("sdfsdf");它是从左边索引为0开始数,而且只找第一个,然后返回该字符的位置.返回是个数值.如果找不到该字符,那么就会返回-1. 返 ...

  7. .NET在WebForm里实现类似WinForm里面TrackBar控件的效果(AJAX Control Toolkit的使用)

    WinForm 里面有一个 TrackBar 控件,表示一个标准的 Windows 跟踪条,是类似于 ScrollBar 控件的可滚动控件.用这个控件可以实现很多可以实时调整的功能,比如最常见的音量调 ...

  8. Microsoft Azure自动化测试

    在使用与微软Azure进行交互的工具并试图衡量性能时,基本上不可能得到任何类似于公平.一致的测试.在午餐时间执行的测试运行会得的一套计时与晚上每个人都离开办公室执行的测试所到的结果可能完全不同.结果取 ...

  9. 100+经典Java面试题及答案解析

    面向对象编程(OOP) Java是一个支持并发.基于类和面向对象的计算机编程语言.下面列出了面向对象软件开发的优点: 代码开发模块化,更易维护和修改. 代码复用. 增强代码的可靠性和灵活性. 增加代码 ...

  10. Oracle-数据实现竖排打印

    --存放重证评分的数据表create table ZZPFapache2(  ZZ_datetime DATE,   --时间  ZZ_zongfen INTEGER, --总分  ZZ_shiwan ...