Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Longest path in 2-D that contains increasing sequence in JavaScript
In JavaScript, finding the longest path in a 2-D array that contains an increasing sequence is a classic dynamic programming problem that can be solved efficiently using memoized depth-first search.
Increasing Sequence
A sequence of numbers in which each succeeding element is greater than the preceding element forms an increasing sequence.
For instance:
4, 6, 8, 9, 11, 14 is an increasing sequence 1, 2, 3, 4, 5 is also an increasing sequence
Problem Statement
We need to write a JavaScript function that takes a 2-D array of numbers and returns the length of the longest path containing only increasing numbers. Movement is allowed in four directions: up, down, left, and right.
For example, if the input array is:
const arr = [ [4, 5, 6], [4, 3, 7], [3, 3, 2] ];
The expected output is:
4
Output Explanation
The longest increasing sequence is 4 ? 5 ? 6 ? 7, which has a length of 4 elements.
Algorithm Visualization
Solution Implementation
const arr = [
[4, 5, 6],
[4, 3, 7],
[3, 3, 2]
];
const longestIncreasingPath = (arr = []) => {
let longest = 0;
let dp = Array(arr.length).fill(null).map(() =>
Array(arr[0].length).fill(1));
const backtracking = (row, col) => {
if (dp[row][col] != 1) return dp[row][col];
let dRow = [1, 0, -1, 0];
let dCol = [0, 1, 0, -1];
for (let i = 0; i = 0 && nR = 0 && nC arr[row][col]) {
dp[row][col] = Math.max(dp[row][col], 1 + backtracking(nR, nC));
}
}
return dp[row][col];
}
for (let i = 0; i
4
How the Algorithm Works
The solution uses memoized depth-first search with the following approach:
Dynamic Programming Array:
dp[i][j]stores the longest increasing path starting from position (i,j)Backtracking Function: For each cell, explores all four directions and recursively calculates the longest path
Memoization: Avoids recalculating paths by storing results in the dp array
Direction Arrays:
dRowanddColrepresent movement in four directions (down, right, up, left)
Time and Space Complexity
| Aspect | Complexity | Explanation |
|---|---|---|
| Time | O(m × n) | Each cell is visited once due to memoization |
| Space | O(m × n) | DP array and recursion stack space |
Alternative Example
const arr2 = [
[1, 2, 3],
[6, 5, 4],
[7, 8, 9]
];
console.log("Array 2 longest path:", longestIncreasingPath(arr2));
Array 2 longest path: 4
Conclusion
The longest increasing path problem is efficiently solved using memoized DFS with O(m×n) time complexity. The key insight is using dynamic programming to avoid recalculating paths, making it much faster than naive backtracking.
