Longest Increasing Path - Amazon Top Interview Questions


Problem Statement :


Given a two-dimensional integer matrix, find the length of the longest strictly increasing path. You can move up, down, left, or right.

Constraints

n, m ≤ 500 where n and m are the number of rows and columns in matrix

Example 1

Input

matrix = [
    [1, 3, 5],
    [0, 4, 6],
    [2, 2, 9]
]

Output

6

Explanation

The longest path is [0, 1, 3, 5, 6, 9]



Solution :



title-img




                        Solution in C++ :

const int dir[4][2] = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}};
int dfs(const vector<vector<int>> &matrix, vector<vector<int>> &dp, const int &r, const int &c) {
    if (dp[r][c] != -1) return dp[r][c];
    dp[r][c] = 1;
    for (int i = 0; i < 4; i++) {
        int nextR = r + dir[i][0];
        int nextC = c + dir[i][1];
        if (nextR < 0 || nextC < 0 || nextR >= matrix.size() || nextC >= matrix[0].size() ||
            matrix[nextR][nextC] <= matrix[r][c]) {
            continue;
        }
        dp[r][c] = max(dp[r][c], 1 + dfs(matrix, dp, nextR, nextC));
    }
    return dp[r][c];
}
int solve(vector<vector<int>> &matrix) {
    int m = matrix.size();
    if (m < 1) return 0;
    int n = matrix[0].size();
    vector<vector<int>> dp(m, vector<int>(n, -1));
    int ans = 0;
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (dp[i][j] == -1) dfs(matrix, dp, i, j);
            ans = max(ans, dp[i][j]);
        }
    }
    return ans;
}
                    


                        Solution in Java :

import java.util.*;

class Solution {
    private int row;
    private int col;
    private int[][] dp;
    private boolean[][] visited;
    private int maxLen = 1;
    public int solve(int[][] matrix) {
        if (matrix == null || matrix.length == 0)
            return 0;
        row = matrix.length;
        col = matrix[0].length;
        dp = new int[row][col];

        for (int[] row : dp) Arrays.fill(row, -1);

        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                maxLen = Math.max(maxLen, dfs(i, j, matrix, -1));
            }
        }
        return maxLen;
    }

    private int dfs(int i, int j, int[][] matrix, int len) {
        if (i < 0 || j < 0 || i >= row || j >= col)
            return 0;

        if (matrix[i][j] <= len)
            return 0;

        if (dp[i][j] != -1)
            return dp[i][j];

        int l1 = dfs(i, j + 1, matrix, matrix[i][j]);
        int l2 = dfs(i, j - 1, matrix, matrix[i][j]);
        int l3 = dfs(i - 1, j, matrix, matrix[i][j]);
        int l4 = dfs(i + 1, j, matrix, matrix[i][j]);

        return dp[i][j] = 1 + Math.max(Math.max(l1, l2), Math.max(l3, l4));
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def solve(self, a):
        if not a or not a[0]:
            return 0
        n, m = len(a), len(a[0])
        dp = [[1 for j in range(m)] for i in range(n)]
        for _, i, j in sorted((a[i][j], i, j) for i in range(n) for j in range(m)):
            for ni, nj in ((i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)):
                if 0 <= ni < n and 0 <= nj < m and a[i][j] < a[ni][nj]:
                    dp[ni][nj] = max(dp[ni][nj], dp[i][j] + 1)
        return max(map(max, dp))
                    


View More Similar Problems

Insert a Node at the Tail of a Linked List

You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink

View Solution →

Insert a Node at the head of a Linked List

Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below

View Solution →

Insert a node at a specific position in a linked list

Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e

View Solution →

Delete a Node

Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value. Example: list=0->1->2->3 position=2 After removing the node at position 2, list'= 0->1->-3. Function Description: Complete the deleteNode function in the editor below. deleteNo

View Solution →

Print in Reverse

Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything. Example head* refers to the linked list with data values 1->2->3->Null Print the following: 3 2 1 Function Description: Complete the reversePrint function in the editor below. reversePrint has the following parameters: Sing

View Solution →

Reverse a linked list

Given the pointer to the head node of a linked list, change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty. Example: head references the list 1->2->3->Null. Manipulate the next pointers of each node in place and return head, now referencing the head of the list 3->2->1->Null. Function Descriptio

View Solution →