You are on page 1of 19

Please refresh this page to receive new updates.

Add Question

Home
Open Questions
Notifications
5

Ganesh

QUESTION TOPICS

Programming Interview Questions


Technical Interview Questions
Programming Interviews
Best of X
Edit Topics
SHARE QUESTION

TwitterFacebook
QUESTION STATS

Views53,149
Followers958

Latest activity: Mon

What are the top 10 most popular dynamic programming


problems among interviewers?
Write Question Details
Follow Question958
Comment1
Share9
Downvote

Write your answer, or answer later.


9 ANSWERS
ASK TO ANSWER

Anant Sharma, Spectator


188 upvotes by Angel Dhiman, Rahul Attuluri, Raja Soni, (more)

Following questions are the most popular dynamic programming problems for interviews :
1. Given a matrix consisting of 0's and 1's, find the maximum size sub-matrix consisting of
only 1's.
2. Given an array containing both positive and negative integers, find the contiguous array
with the maximum sum.
3. Longest Increasing Subsequence - Find the length of the longest subsequence of a given
sequence such that all the elements are sorted in increasing/non-decreasing order.
There are many problems which reduce to the this problem such as box stacking and the
building bridges. These days the interviewers expect an NLogN solution.
4. Edit Distance - Given two strings and a set of operations Change (C), insert (I) and
delete (D) , find minimum number of edits (operations) required to transform one
string into another.

5. 0/1 Knapsack Problem - A thief robbing a store and can carry a maximal weight
of W into their knapsack. There are n items and ith item weigh wiand is
worth vi dollars. What items should thief take?
6. Balanced Partition - You have a set of n integers each in the range 0 K. Partition these
integers into two subsets such that you minimize |S1 S2|, where S1 and S2 denote the
sums of the elements in each of the two subsets.
7. Coin Change - Given a value N, if we want to make change for N cents, and we have
infinite supply of each of S = { S1, S2, .. , Sm} valued coins, how many ways can we make
the change?
8. Longest Common Subsequence - Find the longest common subsequence of two strings
A and B where the elements are letters from the two strings and they should be in the
same order.
9. Longest Palindromic Subsequence - The question is same as above but the subsequence
should be palindromic as well.
10. Minimum Number of Jumps - Given an array of integers where each element represents
the maximum number of steps that can be made forward from that element, find the
minimum number of jumps to reach the end of the array (starting from the first
element).
Written 1 Jan, 2013.
Upvote188
Downvote
Comment
Share4

Gaurav Aggarwal, Computer Science Grad, IIT Delhi


46 upvotes by Shehbaz Jaffer, Vigya Sharma, Charles Caplan, (more)

Here is the list of 10 dynamic programming questions that are commonly asked by
interviewers (I made this list while preparing for interviews):
1. Dice Throw Problem: Given n dice each with m faces, numbered from 1 to m, find
the number of ways to get sum X. X is the summation of values on each face when
all the dice are thrown.
2. Coin Change: You are given n types of coin denominations of values v(1) < v(2) < ... <
v(n) (all integers). Assume v(1) = 1, so you can always make change for any amount of
money C. Give an algorithm which makes change for an amount of money C with as few
coins as possible.
3. Counting Boolean Parenthesizations: You are given a boolean expression
consisting of a string of the symbols 'true', 'false', 'and', 'or', and 'xor'. Count the number
of ways to parenthesize the expression such that it will evaluate to true. For example,
there is only 1 way to parenthesize 'true and false xor true' such that it evaluates to true.

4. Subset Sum Problem: Given a set of non-negative integers, and a value sum,
determine if there is a subset of the given set with sum equal to given sum.
Minimum Number of Jumps: Given an array of integers where each
element represents the maximum number of steps that can be made forward from that
element, find the minimum number of jumps to reach the end of the array (starting
from the first element).
5. Two-Person Traversal of a Sequence of Cities: You are given an ordered
sequence of n cities, and the distances between every pair of cities. You must partition
the cities into two subsequences (not necessarily contiguous) such that person A visits
all cities in the first subsequence (in order), person B visits all cities in the second
subsequence (in order), and such that the sum of the total distances travelled by A and
B is minimized. Assume that person A and person B start initially at the first city in their
respective subsequences.
6. Balanced Partition: You have a set of n integers each in the range 0 ... K. Partition
these integers into two subsets such that you minimize |S1 - S2|, where S1 and S2
denote the sums of the elements in each of the two subsets.
7. Optimal Strategy for a Game: Consider a row of n coins of values v(1) ... v(n), where
n is even. We play a game against an opponent by alternating turns. In each turn, a
player selects either the first or last coin from the row, removes it from the row
permanently, and receives the value of the coin. Determine the maximum possible
amount of money we can definitely win if we move first.
8. Maximum Value Contiguous Subsequence: Given a sequence of n real numbers
A(1) ... A(n), determine a contiguous subsequence A(i) ... A(j) for which the sum of
elements in the subsequence is maximized.
9. Edit Distance: Given two text strings A of length n and B of length m, you want to
transform A into B with a minimum number of operations of the following types: delete
a character from A, insert a character into A, or change some character in A into a new
character. The minimal number of such operations required to transform A into B is
called the edit distance between A and B.
Written 10 Jun, 2013.
Upvote46
Downvote
Comments1+
Share
Ads by GoSaveAd Options

Harry He, Author of <Coding Interviews: ... (more)


39 upvotes by Kritin Vij, Ganesh Raman, Thanh Thai, (more)

Dynamic Programming Interview Questions


The link above collects some problems solved by dynamic programming, such as:

1. Maximum Sum of All Sub-arrays


A sub-array has one number of some continuous numbers. Given an integer array with
positive numbers and negative numbers, get the maximum sum of all sub-arrays. Time
complexity should be O(n).
For example, in the array {1, -2, 3, 10, -4, 7, 2, -5}, its sub-array {3, 10, -4, 7, 2} has
the maximum sum 18.
2. Maximal Length of Incremental Subsequences
Given an unsorted array, find the max length of subsequence in which the numbers are in
incremental order.
For example: If the input array is {7, 2, 3, 1, 5, 8, 9, 6}, a subsequence with the most
numbers in incremental order is {2, 3, 5, 8, 9} and the expected output is 5.
3. Edit Distance
Implement a function which gets the edit distance of two input strings. There are three
types of edit operations: insertion, deletion and substitution. Edit distance is the minimal
number of edit operations to modify a string from one to the other.
4. Minimal Number of Coins for Change
Please implement a function which gets the minimal number of coins, whose value is v1, v2,
, vn, to make change for an amount of money with value t. Any coin with value vi may
duplicate for any times to make change.
For example, the minimal number of coins to make change for 15 out of a set of coins with
value 1, 3, 9, 10 is 3. We can choose two coins with value 3 and a coin with value 9. The
number of coins for other choices should be greater than 3.
5. Dynamic Programming on Stolen Values
There are n houses built in a line, each of which contains some value in it. A thief is going to
steal the maximal value in these houses, but he cannot steal in two adjacent houses because
the owner of a stolen house will tell his two neighbors on the left and right side. What is the
maximal stolen value?
6. Longest Substring without Duplication
Given a string, please get the length of the longest substring which does not have duplicated
characters. Supposing all characters in the string are in the range from a to z.
7. Maximal Product when Cutting Rope
Given a rope with length n, how to cut the rope into m parts with length n[0],n[1], ...,n[m-1],
in order to get the maximal product of n[0]*n[1]* ... *n[m-1]? We have to cut once at least.
Additionally, the length of the whole length of the rope, as well as the length of each part,
are in integer value.
Written 17 Dec, 2013.
Upvote39
Downvote
Comment1

Share

Arpit Agarwal, Have Cracked Interviews of Fac... (more)


42 upvotes by Souptik Sen, Jashwanth Reddy, Rahul Attuluri, (more)

Dynamic Programming Practice Problems


Dynamic Programming Archives - GeeksforGeeks
These links may help you. Most of the DP problems that I have faced in interviews are
covered in these two sites.
Topcoder also has a good collection of DP problems ranging from easy to hard. To gain
confidence in DP I would suggest first go through the above links , then try solving the DP
problems on Topcoder.
Written 30 Dec, 2012.
Upvote42
Downvote
Comment
Share

Abhijeet Nayak, Still figuring it out.


17 upvotes by Priyanshu Jha, Julien Buty, Sada Kurapati, (more)

Checkout following MIT link. It has very good short videos about popular DP problems.
Dynamic Programming Practice Problems
Written 13 Jan.
Upvote17
Downvote
Comment
Share3
Ads by GoSaveAd Options

Chandramouli Raghunath, Interviewed with a bunch of te... (more)


10 upvotes by Mithun Sasidharan, Harshal Godhia, Venkatesh Thallam, (more)

A couple of questions I was asked during the time I interviewed


1. A robot starts from the top left corner(1,1) of a MxN grid. The goal of the robot is to reach
right bottom(M,N). At each step the robot can make one of the two choices - move one cell
right, move one cell bottom. Write a function which takes M and N as arguements and
returns the count of total possible path for the robot to reach its destination.
2. You are standing in front of a staircase which has N stairs. Your goal is to reach the top.
At each step i, you have three choices hop to next step i+1, or i+2 or i+3. Given N, return the
count of total possible paths for you to reach N.
[Edit]
I found a book in Amazon which has a collection of dynamic programming questions!
Amazon.com: A Collection of Dynamic Programming Interview Questions Solved in C++
eBook: Antonio Gulli: Kindle Store
Updated 12 Aug.
Upvote10
Downvote
Comment1
Share

Write your answer, or answer later.


There's more on Quora...
Pick new people and topics to follow and see the best answers on Quora.
Update Your Interests
RELATED QUESTIONS

Off the top of your head what is the most interesting programming problem you know?

What are the best sources for practicing Dynamic Programming problems?

Dynamic programming question to code in 10 min during phone Interview, how reasonable is it?

What are some of the toughest dynamic programming problems which one can face during a technical
interview?

Is Facebook biased towards interview candidates who are top rankers in online programming
competitions?

What are some typical hands-on programming problems given in a software engineer interview?

There is a big file of words which is dynamically changing. We are continuously adding some words into
it. How would you k... (continue)

What happened to Programming Interview Questions | CareerCup? i can't browse the website anymore.
anyone having the same p... (continue)

List of all SPOJ problems which can be a good source for practicing graph algorithms and dynamic
programming?

Programming Interview Questions: Given an expression in the form of a string, solve for x?
More Related Questions

Top Stories from Your Feed


Ads by GoSaveAd Options

And another web site

o
o

o
o
o
o
o

Program Creek

Simple Java
Coding Interview
Java

o
o
o

o
o
o

o
o
o

Design Patterns in Stories


Java Examples
Web Frameworks

Eclipse

Top 10 Algorithms for Coding Interview


By X Wang

PDF Version (updated on 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. The topics that are covered include: String/Array/Matrix, Linked
List, Tree, Heap, Graph, Sorting, Recursion vs. Iteration, Dynamic Programming, Bit
Manipulation, Probability, Combinations and Permutations, and other interesting problems. I
highly recommend you to read"Simple Java" first, if you need a brief review of Java basics.

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
Arrays.sort() //sort an array
Arrays.toString(char[] a) //convert to string
charAt(int x) //get a char at the specific index
length() //string length
length //array size
substring(int beginIndex)
substring(int beginIndex, int endIndex)
Integer.valueOf()//string to integer
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
30) Reverse Words in a String

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 {
int val;
Node next;
Node(int x) {
val = x;
next = null;
}
}

Two popular applications of linked list are stack and queue.


Stack
class Stack{
Node top;
public Node peek(){
if(top != null){

return top;
}
return null;
}
public Node pop(){
if(top == null){
return null;
}else{
Node temp = new Node(top.val);
top = top.next;
return temp;
}
}
public void push(Node n){
if(n != null){
n.next = top;
top = n;
}
}
}

Queue
class Queue{
Node first, last;
public void enqueue(Node n){
if(first == null){
first = n;
last = first;
}else{
last.next = n;
last = n;
}
}
public Node dequeue(){
if(first == null){
return null;
}else{
Node temp = new Node(first.val);
first = first.next;
return temp;
}
}
}

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{
int value;
TreeNode left;
TreeNode right;
}

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
class GraphNode{
int val;
GraphNode next;
GraphNode[] neighbors;
boolean visited;
GraphNode(int x) {
val = x;
}
GraphNode(int x, GraphNode[] n){
val = x;
neighbors = n;
}
public String toString(){
return "value: "+ this.val;
}
}

2) Define a Queue
class Queue{
GraphNode first, last;
public void enqueue(GraphNode n){
if(first == null){
first = n;

last = first;
}else{
last.next = n;
last = n;
}
}
public GraphNode dequeue(){
if(first == null){
return null;
}else{
GraphNode temp = new GraphNode(first.val, first.neighbors);
first = first.next;
return temp;
}
}
}

3) Breath First Search uses a Queue


public class GraphTest {
public static void main(String[] args) {
GraphNode n1 = new GraphNode(1);
GraphNode n2 = new GraphNode(2);
GraphNode n3 = new GraphNode(3);
GraphNode n4 = new GraphNode(4);
GraphNode n5 = new GraphNode(5);
n1.neighbors
n2.neighbors
n3.neighbors
n4.neighbors
n5.neighbors

=
=
=
=
=

new
new
new
new
new

GraphNode[]{n2,n3,n5};
GraphNode[]{n1,n4};
GraphNode[]{n1,n4,n5};
GraphNode[]{n2,n3,n5};
GraphNode[]{n1,n3,n4};

breathFirstSearch(n1, 5);
}
public static void breathFirstSearch(GraphNode root, int x){
if(root.val == x)
System.out.println("find in root");
Queue queue = new Queue();
root.visited = true;
queue.enqueue(root);
while(queue.first != null){
GraphNode c = (GraphNode) queue.dequeue();
for(GraphNode n: c.neighbors){
if(!n.visited){
System.out.print(n + " ");
n.visited = true;
if(n.val == x)
System.out.println("Find "+n);
queue.enqueue(n);
}

}
}
}
}

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

Selection sort

n^2

n^2

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){
if(n <= 2) return n;
int x = f(n-1) + f(n-2);
return x;
}

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.


public static int f(int n) {
if (n <= 2){
return n;
}
int first = 1, second = 2;
int third = 0;
for (int i = 3; i <= n; i++) {
third = first + second;
first = second;
second = third;
}
return third;
}

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.

public static int[] A = new int[100];


public static int f3(int n) {
if (n <= 2)
A[n]= n;
if(A[n] > 0)
return A[n];
else
A[n] = f3(n-1) + f3(n-2);//store results so only calculate once!
return A[n];
}

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){
int result = num & (1<<i);
if(result == 0){
return false;
}else{
return true;
}
}

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.
public static double caculateProbability(int n){
double x = 1;
for(int i=0; i<n; i++){
x *= (365.0-i)/365.0;
}
double pro = Math.round((1-x) * 100);
return pro/100;
}

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
4) Generate Parentheses
Some other problems need us to use observations to form rules to solve them:
1) Reverse Integer
2) Palindrome Number
3) Pow(x,n)
4) Subsets
5) Subsets II

Additional Resources
1. Share your code to Github/BitBucket

You may also like ...


1. How to answer coding questions for your interview?
2. 10
3. Leetcode Solution of Iterative Binary Tree Postorder Traversal in Java
4. LeetCode Merge k Sorted Lists (Java)
Category >> Algorithms >> Interview
If you want to post code, please put the code inside <pre> and </pre> tags.

GEEK
I think the worst-case running time of counting sort is O(N+K), according to the book .
Search

Copyright 2008 - 2014 programcreek.com

Ads by GoSaveAd Options

You might also like