Professional Documents
Culture Documents
Add Question
Home
Open Questions
Notifications
5
Ganesh
QUESTION TOPICS
TwitterFacebook
QUESTION STATS
Views53,149
Followers958
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
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
Share
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
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
o
o
o
o
o
o
o
Program Creek
Simple Java
Coding Interview
Java
o
o
o
o
o
o
o
o
o
Eclipse
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
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;
}
}
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
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;
}
}
}
=
=
=
=
=
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.
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)
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.
Classic problems:
1) Edit Distance
2) Longest Palindromic Substring
3) Word Break
4) Maximum Subarray
8. Bit Manipulation
Bit operators:
OR (|)
AND (&)
XOR (^)
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;
}
}
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
Additional Resources
1. Share your code to Github/BitBucket
GEEK
I think the worst-case running time of counting sort is O(N+K), according to the book .
Search