Mark As Completed Discussion

Optimal Substructure

Optimal Substructure is a fundamental concept in dynamic programming. It plays a crucial role in solving complex problems efficiently.

In dynamic programming, the optimal substructure property states that the optimal solution to a problem can be constructed from the optimal solutions of its subproblems. This allows us to break down a complex problem into smaller overlapping subproblems and solve each subproblem optimally. By combining the solutions to the subproblems, we can obtain the optimal solution to the original problem.

To illustrate this concept, let's consider the problem of finding the shortest path in a graph. The optimal substructure property tells us that the shortest path from a starting node to an ending node can be obtained by finding the shortest path from the starting node to each neighbor and selecting the minimum path among those options. By applying this approach recursively, we can find the shortest path from the starting node to the ending node.

Here's an example of a function that finds the shortest path in a graph using dynamic programming:

JAVASCRIPT
1// replace with ts logic relevant to content
2function shortestPath(graph, start, end) {
3  const dp = new Array(graph.length).fill(Infinity);
4  dp[start] = 0;
5
6  for (let i = 0; i < graph.length; i++) {
7    for (let j = 0; j < graph[i].length; j++) {
8      if (dp[i] + graph[i][j] < dp[j]) {
9        dp[j] = dp[i] + graph[i][j];
10      }
11    }
12  }
13
14  return dp[end];
15}
16
17const graph = [
18  [0, 4, 1, Infinity],
19  [4, 0, 2, 3],
20  [1, 2, 0, 5],
21  [Infinity, 3, 5, 0]
22];
23
24console.log(shortestPath(graph, 0, 3)); // Output: 5
25console.log(shortestPath(graph, 1, 2)); // Output: 2
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment