Dynamic Programming (DP) on Arrays Tutorial
Last Updated :
28 Nov, 2023
We know that Dynamic Programming is a way to reduce the time complexity of a problem using memoization or tabulation of the overlapping states. While applying DP on arrays the array indices act as DP states and transitions occurs between indices.
How to Identify if Array problem has a DP solution?
- Using Constraints: Generally, in Competitive Programming the required solution should perform nearly 10^7 to 10^8 operations, so if the array size N = 1000 to 5000 we can expect to have an N^2 DP solution, and for N = 100 we can have an N^3 DP solution.
- Minimize/Maximize Values: Dynamic Programming can be applied if the problem is to maximize or minimize any value over all possible scenarios.
- Various functions in the problem: If the question consists of functions f(x) as operations then we can try to think towards Dynamic programming.
- Greedy fails: If you can think of a test case where the Greedy solution fails, then the problem has a high chance of having a DP solution.
- Recursive Sub-Problems: Determining whether the problem has a recursive solution where an over-lapping subproblem occurs is a difficult task but if you manage to do that, then DP can be a solution if the constraints allow that.
Quick Approximation of DP Time & Space Complexity for Arrays:
Before coding the solution, we need to verify whether the time complexity of our solution fits the given constraints or not, we can approximate the time complexity using the below formula:
Time Complexity = Total Number of States * ( 1 + Average number of Transitions per State)
Space Complexity = Average number of States.
Why classical-DP problems differ than DP problems on Arrays?
The problems that we see on Competitive Programming platforms are mainly made up of two parts:
The Adhoc part of the problem is the one that makes each problem unique and also the one that decides the difficulty of the problem. One needs to make several observations to deduce the Adhoc part into the standard solution. Good dp problems will often require you to make adhoc observations to figure out some properties that allow you to apply dp on them.
Let's us see how an Adhoc problem changes a standard DP problem:
Problem: You are given N tiles 1 to N, and initially you are standing at 1. In one move you can make a jump of either 1 or 2 in forward direction. Determine the total number of ways you can reach from tile 1 to tile N.
Example: N=4
Output: total 3 ways are possible
Explaination: 1->2->3->4
1->2->4
1->3->4
Adhoc Part: The Adhoc part of the problem diverts the question towards thinking of moving on tiles from 1 to N in different ways, the programmer will dry run several test cases and make several observations in order to reach to the solution, he might even try to make some mathematical formula to calculate the solution.
Standard Part: If observed carefully this question is nothing but print the N'th fibonacci number the simplest DP problem that might exist. each tile T can be reached only via previous two tiles that is T is dependent upon T-1 and T-2. Using This we can write the DP states as:
- Number _of_ways[i]= Number _of_ways[i-1] + Number _of_ways[i-2]
The recurrence relation for the factorial of a number n is given by:
- Factorial [n] = factorial[n-1] * n
The recurrence relation for the inverse factorial of a number n is given by:
- Inverse_fact[n] = (n+1) * (inverse_fact[n+1])
Recognizing which type of Standard DP can be used to solve Array Problems:
When tackling DP problems during a contest the most difficult task is to define the states and transitions for the problem. The states and transitions for problems are mostly the variations of existing standard DP problems, let us see how we can try to think towards a particular standard DP problem:
- Weight/ Volume/Value Constraints in the problem.
- 0-1 decision problem, i.e. either include or exclude an item to the final result.
- Task is to minimize or maximize the profit.
- O(N^2) solution is permissible
- Array values can be used as a denomination on a particular sum.
- Minimum array values required to achieve a target.
- Total number of ways required as a result.
- O(N^2) solution is permissible.
- For a particular index i, dp[i] depends on some previously calculated indices.
- O(N) solution is required.
- State Transition: F(n)=F(n-1) + F(n-2)
- If Each pair of indices {i,j} have to be used as a State then we can try to think towards MCM approach.
- Constraints allow a time complexity of O(N^3)
- dp[i] represents the length of the LIS ending at index i. This idea can be extended to the context where we can calculate the best answer ending at ith index.
- In Edit Distance, dp[i][j] represents the minimum number of operations to convert the first i characters of string1 to the first j characters of string2.
Transition:
- If characters s1[i] and s2[j] are the same: dp[i][j] = dp[i-1][j-1].
- Otherwise: dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1.
The transitions in Edit distance are very commonly seen in many questions where a particular dp value depends upon previously calculated adjacent dp cells.
- In LCS dp[i][j] represents the length of the LCS of the first i characters of string1 and the first j characters of string2.
Transition:
- If characters s1[i] and s2[j] are the same: dp[i][j] = dp[i-1][j-1] + 1.
- Otherwise: dp[i][j] = max(dp[i-1][j], dp[i][j-1]).
Similar to Edit distance, LCS transitions can also be very frequently observed in various problems.
Practice/Solve DP on Array Problems:
Similar Reads
Dynamic Programming or DP Dynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Practice For Cracking Any Coding Interview The coding questions in this article are difficulty-wise ordered. The idea of this post is to target two types of people.Competitive Programming Preparation (For Ist and IInd Year Students): It is recommended to finish all questions from all categories except possibly Linked List, Tree, and BST. How
11 min read
Prefix Sum Array - Implementation and Applications Given an array arr[] of size n, the task is to find the prefix sum of the array. A prefix sum array is another array prefixSum[] of the same size, such that prefixSum[i] is arr[0] + arr[1] + arr[2] . . . arr[i].Examples: Input: arr[] = [10, 20, 10, 5, 15]Output: 10 30 40 45 60Explanation: For each i
8 min read
Competitive Programming - A Complete Guide Competitive Programming is a mental sport that enables you to code a given problem under provided constraints. The purpose of this article is to guide every individual possessing a desire to excel in this sport. This article provides a detailed syllabus for Competitive Programming designed by indust
8 min read
UGC NET Computer Science Syllabus 2024 PDF Download UGC NET is a competitive exam that is conducted by NTAs(National Testing Agency). Computer Science and Applications is one of the popular branches of UGC NET. In this article, we are going to discuss the syllabus of Computer Science and Applications and different terms related to Computer Science an
14 min read
Bits manipulation (Important tactics) Prerequisites: Bitwise operators in C, Bitwise Hacks for Competitive Programming, Bit Tricks for Competitive Programming Table of Contents Compute XOR from 1 to n (direct method)Count of numbers (x) smaller than or equal to n such that n+x = n^xHow to know if a number is a power of 2?Find XOR of all
15+ min read
Introduction to Flowcharts The flowcharts are simple visual tools that help us understand and represent processes very easily. They use shapes like arrows, rectangles, and diamonds to show steps and decisions clearly. If someone is making a project or explaining a complex task, flowcharts can make complex ideas easier to unde
5 min read
Program to print ASCII Value of a character Given a character, we need to print its ASCII value in C/C++/Java/Python. Examples : Input : a Output : 97 Input : DOutput : 68 Here are few methods in different programming languages to print ASCII value of a given character : Python code using ord function : ord() : It converts the given string o
4 min read
Cryptography Hash Functions Cryptographic hash functions are mathematical algorithms that transform input data into a fixed-length sequence of characters, referred to as a hash value. Cryptographic hash functions are intended to be fast, deterministic, and one-way, meaning that even a minor change in input yields a very differ
6 min read
The Painter's Partition Problem Given an array arr[] and k, where the array represents the boards and each element of the given array represents the length of each board. k numbers of painters are available to paint these boards. Consider that each unit of a board takes 1 unit of time to paint. The task is to find the minimum time
15+ min read