AMAZON_HACKON Coding Question – Solved

9 Live
You are given an NxN matrix 'mat' where each cell contains one of the two characters 'a' or 'z'. A man stands at the bottom-right corner of the matrix (mat[N-1][N-1]) and wants to reach the top-left corner of the matrix (mat[0][0]). The man can only move up or left at each step. Your task is to find the lexicographically smallest string that can be formed by following any valid path from mat[N-1][N-1] to mat[0][0]. Additionally, determine the number of distinct paths that yield this lexicographically smallest string. Input Format: First line of input takes integer 'N' denoting the dimensions of the matrix 'mat'. The next 'N' lines take 'N' space-separated characters either 'a' or 'z' representing the values in the matrix 'mat'. Output Format: The first line of output shows the lexicographically smallest string that can be formed by any valid path from mat[N-1][N-1] to mat[0][0]. The last line of the output shows the number of distinct paths that yield this lexicographically smallest string. Constraints: 2 <= N <= 40 Sample Testcase 1 Input: 3 z a z a a a z z z Output: zaaaz 2 Explanation: Starting from mat[2][2] = 'z', the next move can either be up or left. If we move up to mat[1][2] = 'a', then move left to mat[1][1] = 'a', then move either up or left to mat[1][0] or mat[0][1] = 'a', and finally move up to mat[0][0] = 'z', the path forms the string "zaaaz", the lexicographically smallest string. Therefore, the number of possible paths = 2. Sample Testcase 2 Input: 4 z z a z z z a a z z a z a a a a Output: aaaaazz 1 Explanation: Starting from mat[3][3] = 'a', the next move can either be up or left. Moving up to mat[2][3] = 'a', then up to mat[1][3] = 'a', then up to mat[0][3] = 'a', then left to mat[0][2] = 'a', then left to mat[0][1] = 'z', and finally left to mat[0][0] = 'z', the path forms the string "aaaaazz", which is the lexicographically smallest string. Therefore, the number of possible paths that form the string is 1.

Asked in: AMAZON_HACKON

Image of the Question

Question Image Question Image Question Image Question Image

All Testcases Passed ✔



Passcode Image

Solution


#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
// ... rest of solution available after purchase

🔒 Please login to view the solution

Explanation


```
This problem requires determining two things simultaneously: (1) the lexicographically smallest string that can be formed by moving from the bottom-right corner to the top-left corner of an NxN matrix following only upward or leftward moves, and (2) the count of distinct paths that yield this lexicographically smallest string.

To approach this, break down the problem into logical parts and understand the constraints and properties involved.

1. **Understanding the movement constraints and path characteristics**
Since the man can only move up or left starting from the bottom-right cell (mat[N-1][N-1]) towards the top-left cell (mat[0][0]), each path consists of exactly 2*(N-1) moves (N-1 moves up and N-1 moves left in some order). The length of the string formed by concatenating characters along any valid path is always 2*N - 1 because you start at one cell and move 2*(N-1) times.

2. **Lexicographically smallest string from paths**
Each path yields a string by concatenating the characters of the cells visited, starting from mat[N-1][N-1] and moving step-by-step up or left until reaching mat[0][0]. The problem is to find among all possible paths the one(s) with the lexicographically smallest resulting string.

3. **Key observations about lex order and movement**
Because we can only move up or left, the problem naturally has overlapping subproblems and structure amenable to dynamic programming or BFS/DFS with pruning. At each step, from any given cell, we can explore the two possible moves (if valid), and continue building possible strings.

4. **Challenge: Exploring paths efficiently and comparing lex order**
Enumerating all paths explicitly would be exponential and infeasible for N up to 40. Thus, a naive brute force approach is impractical. Instead, focus on maintaining and propagating only the lexicographically smallest strings achievable to each cell, along with the number of ways to achieve that smallest string.

5. **Dynamic Programming Approach**
Define a DP structure where for each cell (i, j), you store:
- The lexicographically smallest string possible to reach cell (i, j) from the start position (bottom-right).
- The count of distinct paths that yield this smallest string.

Since we start from mat[N-1][N-1] and move backward toward mat[0][0], consider building this DP from bottom-right to top-left, or alternatively build from top-left to bottom-right by reversing the direction of moves (considering allowed moves accordingly).

6. **Transition of DP states**
For each cell, the lexicographically smallest string to reach it depends on the strings from cells reachable by moving up or left from that cell (or conversely, if building backward, from cells moving down or right). For a cell (i, j), check the cells (i+1, j) and (i, j+1) if valid, which represent the cells reachable by moving up or left in the reversed direction. Then:
- Compare the lexicographically smallest strings from those neighbors.
- Pick the lexicographically smaller string(s).
- Append the current cell’s character to these strings.
- Sum the counts of paths if multiple neighbors have the same smallest string.

7. **String comparison efficiency**
Storing and comparing full strings for each cell might be costly in terms of memory and computation. However, since the strings are formed along fixed-length paths (length 2*N-1), and characters are only 'a' or 'z', it can be optimized. Still, the straightforward approach involves storing partial strings or storing references to parent states.

8. **Path Counting**
Once you determine the lexicographically smallest string for a cell, also keep track of how many distinct ways that string can be formed by summing up the counts from predecessor cells which also yield that smallest string. This way, you accumulate the number of valid paths for each DP state.

9. **Boundary Conditions**
The starting cell (bottom-right) has a known string (just its own character) and count = 1. Proceed to fill DP table towards top-left. Handle edges carefully because at the boundaries you only have one possible move.

10. **Result extraction**
After filling the DP table for all cells, the answer will be the lexicographically smallest string and count stored at the target cell (mat[0][0]).

11. **Example walk-through**
Using the sample test cases, verify that at each cell you correctly propagate the smallest strings and counts from neighbors, and the final answer matches the sample output.

12. **Additional notes and optimizations**
- Since characters are only 'a' or 'z', lexicographic comparison simplifies to comparing sequences of these two characters.
- You can also store partial strings as arrays or strings in DP states or represent them using indices and reconstruct later.
- For memory optimization, only maintain DP states for the current and next row (or column), if building in a certain order.

In conclusion, focus on dynamic programming that tracks for each cell the lexicographically smallest string achievable and how many distinct ways it can be formed by considering allowed moves and aggregating path counts. This approach balances correctness and feasibility given the input constraints.
```


Related Questions