Top 10 Algorithms for Coding Interview
The following are the common subjects in coding interviews. As understanding those concepts requires much more effort, this tutorial only serves as an introduction. The subjects that are covered include: 1) String/Array/Matrix, 2) Linked List, 3) Tree, 4) Heap, 5) Graph, 6) Sorting, 7) Dynamic Programming, 8) Bit Manipulation, 9) Combinations and Permutations, and 10) Math Problems. I highly recommend you to read "Simple Java" first, if you need a brief review of Java basics. If you want to see code examples that show how to use a popular API, you can use JavaSED.com.
1. String/Array
An algorithm problem's input is often a string or array. Without auto-completion of any IDE, the following methods should be remembered.
Classic problems:
--Two Pointers--
1) Rotate Array, Reverse Words in a String
2) Evaluate Reverse Polish Notation (Stack)
3) Isomorphic Strings
4) Word Ladder (BFS), Word Ladder II (BFS)
5) Median of Two Sorted Arrays
5) Kth Largest Element in an Array
6) Wildcard Matching, Regular Expression Matching
7) Merge Intervals, Insert Interval
9) Two Sum, Two Sum II, Two Sum III, 3Sum, 4Sum
10) 3Sum Closest
11) String to Integer
12) Merge Sorted Array
13) Valid Parentheses
13) Longest Valid Parentheses
14) Implement strStr()
15) Minimum Size Subarray Sum
16) Search Insert Position
17) Longest Consecutive Sequence
18) Valid Palindrome
19) ZigZag Conversion
20) Add Binary
21) Length of Last Word
22) Triangle
24) Contains Duplicate: I, II, III
25) Remove Duplicates from Sorted Array: I, II, Remove Element , Move Zeroes
27) Longest Substring Without Repeating Characters
28) Longest Substring that contains 2 unique characters [Google]
28) Substring with Concatenation of All Words
29) Minimum Window Substring
31) Find Minimum in Rotated Sorted Array: I, II
32) Search in Rotated Array:I, II
33) Min Stack
34) Majority Element: I, II
35) Bulls and Cows
36) Largest Rectangle in Histogram
37) Longest Common Prefix [Google]
38) Largest Number
39) Simplify Path
40) Compare Version Numbers
41) Gas Station
44) Pascal's Triangle: I, II
45) Container With Most Water
45) Candy [Google]
45) Trapping Rain Water
46) Count and Say
47) Search for a Range
48) Basic Calculator, Basic Calculator II
49) Group Anagrams
50) Shortest Palindrome
51) Rectangle Area
52) Summary Ranges
53) Increasing Triplet Subsequence
54) Get Target Using Number List And Arithmetic Operations
55) Reverse Vowels of a String
56) Flip Game, Flip Game II
57) Missing Number, Find the duplicate number, First Missing Positive
58) Valid Anagram, Group Shifted Strings
59) Top K Frequent Elements
60) Find Peak Element
61) Word Pattern, Word Pattern II
62) H-Index , H-Index II
63) Palindrome Pairs
64) One Edit Distance
65) Scramble String
66) First Bad Version
67) Integer to English Words
68) Text Justification
69) Remove Invalid Parentheses
70) Intersection of Two Arrays, Intersection of Two Arrays II
71) Sliding Window Maximum, Moving Average from Data Stream
72) Guess Number Higher or Lower
--Two Pointers--
1) Rotate Array, Reverse Words in a String
2) Evaluate Reverse Polish Notation (Stack)
3) Isomorphic Strings
4) Word Ladder (BFS), Word Ladder II (BFS)
5) Median of Two Sorted Arrays
5) Kth Largest Element in an Array
6) Wildcard Matching, Regular Expression Matching
7) Merge Intervals, Insert Interval
9) Two Sum, Two Sum II, Two Sum III, 3Sum, 4Sum
10) 3Sum Closest
11) String to Integer
12) Merge Sorted Array
13) Valid Parentheses
13) Longest Valid Parentheses
14) Implement strStr()
15) Minimum Size Subarray Sum
16) Search Insert Position
17) Longest Consecutive Sequence
18) Valid Palindrome
19) ZigZag Conversion
20) Add Binary
21) Length of Last Word
22) Triangle
24) Contains Duplicate: I, II, III
25) Remove Duplicates from Sorted Array: I, II, Remove Element , Move Zeroes
27) Longest Substring Without Repeating Characters
28) Longest Substring that contains 2 unique characters [Google]
28) Substring with Concatenation of All Words
29) Minimum Window Substring
31) Find Minimum in Rotated Sorted Array: I, II
32) Search in Rotated Array:I, II
33) Min Stack
34) Majority Element: I, II
35) Bulls and Cows
36) Largest Rectangle in Histogram
37) Longest Common Prefix [Google]
38) Largest Number
39) Simplify Path
40) Compare Version Numbers
41) Gas Station
44) Pascal's Triangle: I, II
45) Container With Most Water
45) Candy [Google]
45) Trapping Rain Water
46) Count and Say
47) Search for a Range
48) Basic Calculator, Basic Calculator II
49) Group Anagrams
50) Shortest Palindrome
51) Rectangle Area
52) Summary Ranges
53) Increasing Triplet Subsequence
54) Get Target Using Number List And Arithmetic Operations
55) Reverse Vowels of a String
56) Flip Game, Flip Game II
57) Missing Number, Find the duplicate number, First Missing Positive
58) Valid Anagram, Group Shifted Strings
59) Top K Frequent Elements
60) Find Peak Element
61) Word Pattern, Word Pattern II
62) H-Index , H-Index II
63) Palindrome Pairs
64) One Edit Distance
65) Scramble String
66) First Bad Version
67) Integer to English Words
68) Text Justification
69) Remove Invalid Parentheses
70) Intersection of Two Arrays, Intersection of Two Arrays II
71) Sliding Window Maximum, Moving Average from Data Stream
72) Guess Number Higher or Lower
2. Matrix
Common methods to solve matrix related problem include DFS, BFS, dynamic programming, etc.
Classic Problems:
1) Set Matrix Zeroes
2) Spiral Matrix
2) Spiral Matrix II
3) Search a 2D Matrix
3) Search a 2D Matrix II
4) Rotate Image [Palantir]
5) Valid Sudoku
6) Minimum Path Sum (DP) [Google]
7) Unique Paths (DP) [Google]
7) Unique Paths II (DP)
8) Number of Islands (DFS/BFS), Number of Islands II (Disjoint Set), Number of Connected Components in an Undirected Graph
9) Surrounded Regions (BFS)
10) Maximal Rectangle
10) Maximal Square
11) Word Search (DFS)
11) Word Search II
13) Range Sum Query 2D – Immutable
14) Longest Increasing Path in a Matrix (DFS)
15) Shortest Distance from All Buildings
16) Game of Life
17) Paint House, Paint House II
18) Sudoku Solver (DFS)
19) Walls and Gates (DFS/BFS)
20) Tic-Tac-Toe
21) Best Meeting Point
1) Set Matrix Zeroes
2) Spiral Matrix
2) Spiral Matrix II
3) Search a 2D Matrix
3) Search a 2D Matrix II
4) Rotate Image [Palantir]
5) Valid Sudoku
6) Minimum Path Sum (DP) [Google]
7) Unique Paths (DP) [Google]
7) Unique Paths II (DP)
8) Number of Islands (DFS/BFS), Number of Islands II (Disjoint Set), Number of Connected Components in an Undirected Graph
9) Surrounded Regions (BFS)
10) Maximal Rectangle
10) Maximal Square
11) Word Search (DFS)
11) Word Search II
13) Range Sum Query 2D – Immutable
14) Longest Increasing Path in a Matrix (DFS)
15) Shortest Distance from All Buildings
16) Game of Life
17) Paint House, Paint House II
18) Sudoku Solver (DFS)
19) Walls and Gates (DFS/BFS)
20) Tic-Tac-Toe
21) Best Meeting Point
3. Linked List
The implementation of a linked list is pretty simple in Java. Each node has a value and a link to next node.
Two popular applications of linked list are stack and queue.
Stack
Queue
The Java standard library contains a class called "Stack". Another class from Java SDK is LinkedList, which can be used as a Queue (add() and remove()). (LinkedList implements the Queue interface.) If a stack or queue is required to solve problems during your interview, they are ready to be used.
Classic Problems:
0) Implement a Stack Using an Array
1) Add Two Numbers
2) Reorder List
3) Linked List Cycle
4) Copy List with Random Pointer
5) Merge Two Sorted Lists
6) Odd Even Linked List
7) Remove Duplicates from Sorted List
7) Remove Duplicates from Sorted List II
8) Partition List
9) LRU Cache
10) Intersection of Two Linked Lists
11) Remove Linked List Elements
12) Swap Nodes in Pairs
13) Reverse Linked List, Reverse Linked List II, Print Linked List in Reversed Order
14) Remove Nth Node From End of List (Fast-Slow Pointers)
15) Implement Stack using Queues
15) Implement Queue using Stacks
16) Palindrome Linked List
17) Implement a Queue using an Array
18) Delete Node in a Linked List
19) Reverse Nodes in k-Group
0) Implement a Stack Using an Array
1) Add Two Numbers
2) Reorder List
3) Linked List Cycle
4) Copy List with Random Pointer
5) Merge Two Sorted Lists
6) Odd Even Linked List
7) Remove Duplicates from Sorted List
7) Remove Duplicates from Sorted List II
8) Partition List
9) LRU Cache
10) Intersection of Two Linked Lists
11) Remove Linked List Elements
12) Swap Nodes in Pairs
13) Reverse Linked List, Reverse Linked List II, Print Linked List in Reversed Order
14) Remove Nth Node From End of List (Fast-Slow Pointers)
15) Implement Stack using Queues
15) Implement Queue using Stacks
16) Palindrome Linked List
17) Implement a Queue using an Array
18) Delete Node in a Linked List
19) Reverse Nodes in k-Group
4. Tree, Heap and Trie
A tree normally refers to a binary tree. Each node contains a left node and right node like the following:
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.
4.1 Tree
1) Binary Tree Traversal: Preorder, Inorder, Postorder, Level Order, Level Order II, Vertical Order
2) Invert Binary Tree
3) Kth Smallest Element in a BST
4) Binary Tree Longest Consecutive Sequence
5) Validate Binary Search Tree
6) Flatten Binary Tree to Linked List
7) Path Sum (DFS or BFS)
7) Path Sum II (DFS)
8) Construct Binary Tree from Inorder and Postorder Traversal
8) Construct Binary Tree from Preorder and Inorder Traversal
9) Convert Sorted Array to Binary Search Tree [Google]
10) Convert Sorted List to Binary Search Tree [Google]
11) Minimum Depth of Binary Tree
12) Binary Tree Maximum Path Sum *
13) Balanced Binary Tree
14) Symmetric Tree
15) Binary Search Tree Iterator
16) Binary Tree Right Side View
17) Lowest Common Ancestor of a Binary Search Tree
18) Lowest Common Ancestor of a Binary Tree
19) Verify Preorder Serialization of a Binary Tree
20) Populating Next Right Pointers in Each Node
21) Populating Next Right Pointers in Each Node II
21) Unique Binary Search Trees (DP)
21) Unique Binary Search Trees II (DFS)
22) Sum Root to Leaf Numbers (DFS)
23) Count Complete Tree Nodes
24) Closest Binary Search Tree Value
25) Binary Tree Paths
26) Maximum Depth of Binary Tree
27 Recover Binary Search Tree
28) Same Tree
29) Serialize and Deserialize Binary Tree
30) Inorder Successor in BST
31) Find Leaves of Binary Tree
32) Largest BST Subtree
2) Invert Binary Tree
3) Kth Smallest Element in a BST
4) Binary Tree Longest Consecutive Sequence
5) Validate Binary Search Tree
6) Flatten Binary Tree to Linked List
7) Path Sum (DFS or BFS)
7) Path Sum II (DFS)
8) Construct Binary Tree from Inorder and Postorder Traversal
8) Construct Binary Tree from Preorder and Inorder Traversal
9) Convert Sorted Array to Binary Search Tree [Google]
10) Convert Sorted List to Binary Search Tree [Google]
11) Minimum Depth of Binary Tree
12) Binary Tree Maximum Path Sum *
13) Balanced Binary Tree
14) Symmetric Tree
15) Binary Search Tree Iterator
16) Binary Tree Right Side View
17) Lowest Common Ancestor of a Binary Search Tree
18) Lowest Common Ancestor of a Binary Tree
19) Verify Preorder Serialization of a Binary Tree
20) Populating Next Right Pointers in Each Node
21) Populating Next Right Pointers in Each Node II
21) Unique Binary Search Trees (DP)
21) Unique Binary Search Trees II (DFS)
22) Sum Root to Leaf Numbers (DFS)
23) Count Complete Tree Nodes
24) Closest Binary Search Tree Value
25) Binary Tree Paths
26) Maximum Depth of Binary Tree
27 Recover Binary Search Tree
28) Same Tree
29) Serialize and Deserialize Binary Tree
30) Inorder Successor in BST
31) Find Leaves of Binary Tree
32) Largest BST Subtree
4.2 Heap
1) Merge k sorted arrays [Google]
2) Merge k Sorted Lists *
3) Find Median from Data Stream
4) Meeting Rooms II, Meeting Rooms
5) Range Addition
2) Merge k Sorted Lists *
3) Find Median from Data Stream
4) Meeting Rooms II, Meeting Rooms
5) Range Addition
4.3 Trie
4.4 Segment Tree
5. 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
2) Define a Queue
3) Breath First Search uses a Queue
Output:
value: 2 value: 3 value: 5 Find value: 5
value: 4
value: 4
Classic Problems:
1) Clone Graph
2) Course Schedule , Course Schedule II , Minimum Height Trees
3) Reconstruct Itinerary
4) Graph Valid Tree
1) Clone Graph
2) Course Schedule , Course Schedule II , Minimum Height Trees
3) Reconstruct Itinerary
4) Graph Valid Tree
6. 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.
4) Maximum Gap (Bucket Sort)
5) Sort Colors (Counting Sort)
1) Mergesort
2) Quicksort
3) InsertionSort.
4) Maximum Gap (Bucket Sort)
5) Sort Colors (Counting Sort)
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.
Classic problems:
1) Edit Distance
1) Distinct Subsequences Total
2) Longest Palindromic Substring
3) Word Break
3) Word Break II
4) Maximum Subarray
4) Maximum Product Subarray
5) Palindrome Partitioning
5) Palindrome Partitioning II
6) House Robber [Google]
6) House Robber II
6) House Robber III
7) Jump Game
7) Jump Game II
8) Best Time to Buy and Sell Stock
8) Best Time to Buy and Sell Stock II
8) Best Time to Buy and Sell Stock III
8) Best Time to Buy and Sell Stock IV
9) Dungeon Game
10) Minimum Path Sum
11) Unique Paths
12) Decode Ways
13) Longest Common Subsequence
14) Longest Common Substring
15) Longest Increasing Subsequence
16) Coin Change
17) Perfect Squares
1) Edit Distance
1) Distinct Subsequences Total
2) Longest Palindromic Substring
3) Word Break
3) Word Break II
4) Maximum Subarray
4) Maximum Product Subarray
5) Palindrome Partitioning
5) Palindrome Partitioning II
6) House Robber [Google]
6) House Robber II
6) House Robber III
7) Jump Game
7) Jump Game II
8) Best Time to Buy and Sell Stock
8) Best Time to Buy and Sell Stock II
8) Best Time to Buy and Sell Stock III
8) Best Time to Buy and Sell Stock IV
9) Dungeon Game
10) Minimum Path Sum
11) Unique Paths
12) Decode Ways
13) Longest Common Subsequence
14) Longest Common Substring
15) Longest Increasing Subsequence
16) Coin Change
17) Perfect Squares
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)
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;
1<<1= 10 1010&10=10 10 is not 0, so return true;
Classic Problems:
1) Single Number
1) Single Number II
2) Maximum Binary Gap
3) Number of 1 Bits
4) Reverse Bits
5) Repeated DNA Sequences
6) Bitwise AND of Numbers Range
7) Sum of Two Integers
8) Counting Bits
9) Maximum Product of Word Lengths
10) Gray Code
1) Single Number
1) Single Number II
2) Maximum Binary Gap
3) Number of 1 Bits
4) Reverse Bits
5) Repeated DNA Sequences
6) Bitwise AND of Numbers Range
7) Sum of Two Integers
8) Counting Bits
9) Maximum Product of Word Lengths
10) Gray Code
9. 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
4) Generate Parentheses
5) Combination Sum (DFS), II (DFS), III (DFS), IV (DP)
6) Combinations (DFS)
7) Letter Combinations of a Phone Number (DFS)
8) Restore IP Addresses
9) Factor Combinations (DFS)
1) Permutations
2) Permutations II
3) Permutation Sequence
4) Generate Parentheses
5) Combination Sum (DFS), II (DFS), III (DFS), IV (DP)
6) Combinations (DFS)
7) Letter Combinations of a Phone Number (DFS)
8) Restore IP Addresses
9) Factor Combinations (DFS)
10. Math
Solving math problems usually require us to find regularities or repeated pattern from the observations. List the results for a small set of numbers first, if you do not have any ideas.
1) Reverse Integer
2) Palindrome Number
3) Pow(x,n), Power of Two, Power of Three, Power of Four
4) Subsets
5) Subsets II
6) Fraction to Recurring Decimal [Google]
7) Excel Sheet Column Number
8) Excel Sheet Column Title
9) Factorial Trailing Zeroes
10) Happy Number
11) Count Primes
12) Plus One
13) Divide Two Integers
14) Multiply Strings
15) Max Points on a Line
16) Product of Array Except Self
17) Integer Break
18) Add Digits
21) Ugly Number, 9Ugly Number II, Super Ugly Number, Find K Pairs with Smallest Sums
2) Palindrome Number
3) Pow(x,n), Power of Two, Power of Three, Power of Four
4) Subsets
5) Subsets II
6) Fraction to Recurring Decimal [Google]
7) Excel Sheet Column Number
8) Excel Sheet Column Title
9) Factorial Trailing Zeroes
10) Happy Number
11) Count Primes
12) Plus One
13) Divide Two Integers
14) Multiply Strings
15) Max Points on a Line
16) Product of Array Except Self
17) Integer Break
18) Add Digits
21) Ugly Number, 9Ugly Number II, Super Ugly Number, Find K Pairs with Smallest Sums
UPDATE: I decided to add more categories below.
11. HashMap
Great article. Links mentioned in your blog were very useful. Thanks for sharing.
답글삭제Cheers,
http://www.flowerbrackets.com/how-to-implement-quick-sort-in-java-program/
Awesome!!! The algorithms mentioned in your article were very useful. Thanks for sharing.
답글삭제Cheers,
http://www.flowerbrackets.com/pascal-triangle-in-java/
Nice explanation with appropriate links. Thanks for sharing.
답글삭제Cheers,
http://www.flowerbrackets.com/palindrome-number-in-java/