1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. 2d Dynamic Programming
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
11Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. 2d Dynamic Programming

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
11Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

2D Dynamic Programming

Overview

2D Dynamic Programming applies the exact same caching concept to problems where the state depends on Two changing variables. Because there are two dimensions to track, the cache requires a 2D Array (a Matrix).

A classic example is finding the number of 'Unique Paths' a robot can take on a Grid from the top-left to the bottom-right, only being allowed to move down or right. The robot's state is defined by its Row (y) and its Column (x).

The mathematical beauty of this problem is that the number of unique ways to reach cell (y, x) is simply the sum of the ways to reach the cell directly above it PLUS the ways to reach the cell directly to its left.

By storing these results in a dp[row][col] matrix, an exponential recursive maze-solving problem becomes a lightning-fast, simple nested loop.

Syntax

Unique Paths in a Grid
java
public class DP2D {
    public int uniquePaths(int rows, int cols) {
        // Create 2D cache
        int[][] dp = new int[rows][cols];
        
        // Base case: There is only 1 way to travel along the top edge or left edge 
        // (because you can only move in a straight line to reach them)
        for (int i = 0; i < rows; i++) dp[i][0] = 1;
        for (int j = 0; j < cols; j++) dp[0][j] = 1;
        
        // Fill the grid based on previous results
        for (int i = 1; i < rows; i++) {
            for (int j = 1; j < cols; j++) {
                // The number of ways to reach THIS cell is the sum of ways to reach 
                // the cell strictly above it AND strictly to the left of it.
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
            }
        }
        
        // The bottom-right cell contains the final accumulated answer
        return dp[rows - 1][cols - 1];
    }
}

Common Pitfalls

  • Initializing boundaries incorrectly. If you forget to populate the 0th row and 0th column, your algorithm will just sum zeros infinitely.
  • Extremely high memory consumption. A 2D array of size 10,000 x 10,000 consumes 400MB of RAM. 2D DP algorithms are notorious memory hogs if not aggressively optimized.
  • Index Out of Bounds. Always double check your i-1 and j-1 logic. Your nested loops must start at index 1 to avoid querying negative indices.

Interview Questions

Can 2D DP space complexity be optimized?

Yes, incredibly well. In the Unique Paths problem, calculating the current row only requires data from the current row and the previous row. You can completely discard all older rows. This drops the Space Complexity from O(Rows * Cols) down to just O(Cols) by using a 1D array.

What is the Longest Common Subsequence (LCS)?

It is one of the most famous 2D DP problems. Given two strings, you find the longest sequence of characters that appear in both in the same order. It uses a 2D matrix where rows represent string A and columns represent string B.

Real-World Example

Levenshtein Distance for Spell Checking and DNA sequencing. When you misspell 'algorhythm', how does Google know to suggest 'algorithm'? It uses a 2D DP algorithm (Edit Distance) that compares two strings character by character in a matrix, calculating the minimum number of insertions, deletions, or substitutions required to transform one string into the other.

example
java
public class SpellChecker {
    // 2D DP to calculate Minimum Edit Distance
    public int minDistance(String word1, String word2) {
        int m = word1.length(), n = word2.length();
        int[][] dp = new int[m + 1][n + 1];
        
        for (int i = 0; i <= m; i++) dp[i][0] = i;
        for (int j = 0; j <= n; j++) dp[0][j] = j;
        
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1]; // Characters match, no cost
                } else {
                    // Min of Replace, Delete, or Insert
                    dp[i][j] = Math.min(dp[i - 1][j - 1], 
                               Math.min(dp[i - 1][j], dp[i][j - 1])) + 1;
                }
            }
        }
        return dp[m][n];
    }
}

Check Your Knowledge

Test your understanding of 2D Dynamic Programming with these quick questions.

Question 1

Why use a 2D array instead of a 1D array for these specific problems?

Question 2

In the Unique Paths grid problem, what is the base case for the top row?

Question 3

What is the Space Complexity of standard 2D DP without optimization?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

2D Dynamic Programming

Overview

2D Dynamic Programming applies the exact same caching concept to problems where the state depends on Two changing variables. Because there are two dimensions to track, the cache requires a 2D Array (a Matrix).

A classic example is finding the number of 'Unique Paths' a robot can take on a Grid from the top-left to the bottom-right, only being allowed to move down or right. The robot's state is defined by its Row (y) and its Column (x).

The mathematical beauty of this problem is that the number of unique ways to reach cell (y, x) is simply the sum of the ways to reach the cell directly above it PLUS the ways to reach the cell directly to its left.

By storing these results in a dp[row][col] matrix, an exponential recursive maze-solving problem becomes a lightning-fast, simple nested loop.

Syntax

Unique Paths in a Grid
java
public class DP2D {
    public int uniquePaths(int rows, int cols) {
        // Create 2D cache
        int[][] dp = new int[rows][cols];
        
        // Base case: There is only 1 way to travel along the top edge or left edge 
        // (because you can only move in a straight line to reach them)
        for (int i = 0; i < rows; i++) dp[i][0] = 1;
        for (int j = 0; j < cols; j++) dp[0][j] = 1;
        
        // Fill the grid based on previous results
        for (int i = 1; i < rows; i++) {
            for (int j = 1; j < cols; j++) {
                // The number of ways to reach THIS cell is the sum of ways to reach 
                // the cell strictly above it AND strictly to the left of it.
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
            }
        }
        
        // The bottom-right cell contains the final accumulated answer
        return dp[rows - 1][cols - 1];
    }
}

Common Pitfalls

  • Initializing boundaries incorrectly. If you forget to populate the 0th row and 0th column, your algorithm will just sum zeros infinitely.
  • Extremely high memory consumption. A 2D array of size 10,000 x 10,000 consumes 400MB of RAM. 2D DP algorithms are notorious memory hogs if not aggressively optimized.
  • Index Out of Bounds. Always double check your i-1 and j-1 logic. Your nested loops must start at index 1 to avoid querying negative indices.

Interview Questions

Can 2D DP space complexity be optimized?

Yes, incredibly well. In the Unique Paths problem, calculating the current row only requires data from the current row and the previous row. You can completely discard all older rows. This drops the Space Complexity from O(Rows * Cols) down to just O(Cols) by using a 1D array.

What is the Longest Common Subsequence (LCS)?

It is one of the most famous 2D DP problems. Given two strings, you find the longest sequence of characters that appear in both in the same order. It uses a 2D matrix where rows represent string A and columns represent string B.

Real-World Example

Levenshtein Distance for Spell Checking and DNA sequencing. When you misspell 'algorhythm', how does Google know to suggest 'algorithm'? It uses a 2D DP algorithm (Edit Distance) that compares two strings character by character in a matrix, calculating the minimum number of insertions, deletions, or substitutions required to transform one string into the other.

example
java
public class SpellChecker {
    // 2D DP to calculate Minimum Edit Distance
    public int minDistance(String word1, String word2) {
        int m = word1.length(), n = word2.length();
        int[][] dp = new int[m + 1][n + 1];
        
        for (int i = 0; i <= m; i++) dp[i][0] = i;
        for (int j = 0; j <= n; j++) dp[0][j] = j;
        
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1]; // Characters match, no cost
                } else {
                    // Min of Replace, Delete, or Insert
                    dp[i][j] = Math.min(dp[i - 1][j - 1], 
                               Math.min(dp[i - 1][j], dp[i][j - 1])) + 1;
                }
            }
        }
        return dp[m][n];
    }
}

Check Your Knowledge

Test your understanding of 2D Dynamic Programming with these quick questions.

Question 1

Why use a 2D array instead of a 1D array for these specific problems?

Question 2

In the Unique Paths grid problem, what is the base case for the top row?

Question 3

What is the Space Complexity of standard 2D DP without optimization?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A