Amazon Interview Question for SDE-3s

• 0

Country: United States
Interview Type: In-Person

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````'use strict';

/**
* empty space - 0
* door - 1
* wall - 2
* visited cell - 3
*/
const grid = [
[2, 1, 2, 1, 2, 2, 2],
[2, 0, 2, 0, 0, 0, 2],
[2, 0, 0, 2, 2, 0, 2],
[2, 2, 0, 2, 0, 0, 2],
[2, 0, 0, 0, 0, 0, 2],
[2, 2, 2, 0, 0, 0, 2],
[2, 2, 2, 2, 2, 2, 2]
];

const directions = [
{ dx: 1, dy: 0 }, /* right */
{ dx: 0, dy: 1 }, /* down */
{ dx: -1, dy: 0 }, /* left */
{ dx: 0, dy: -1 } /* up */
];

function findShortestWayToDoor(startY, startX, grid) {
if(grid[startY][startX] === 2) {
throw new Error('feels bad to be put in a wall');
}

const coordinates = [{ x: startX, y: startY, steps: 0 }];

while(coordinates.length) {
const { x, y, steps } = coordinates.pop();

if(grid[y][x] === 1) {
return steps;
}

grid[y][x] = 3;

directions.forEach(({ dx, dy }) => {
if(grid[y + dy][x + dx] < 2) {
coordinates.unshift({ x: x + dx, y: y + dy, steps: steps + 1 });
}
});
}

return -1; // no doors found
}

const stepsToNearestDoor = findShortestWayToDoor(5, 4, grid);

console.log(stepsToNearestDoor);``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

For both parts of the question, the right way to go seems BFS.
For the first part the start position would be the random input point and stop when you reach a door.
For the second part enqueue all the points where there are doors. Each position gets its discoverer's distance plus 1. Stop when the queue is empty.
Note that it's possible that one or more points are left unmarked. These points don't have access to any door and can be marked with -1 or MAXINT after the BFS process completes.

Comment hidden because of low score. Click to expand.
0
of 0 vote

BFS is the right way to go ... Also you can create an adapter class for the grid/matrix to navigate from any node in the four possible directions and simply use the text book algorithm for BFS. Below is a C# implementation

``````public enum NodeStatus
{
Undiscovered,
Discovered,
Processed
}

/// <summary>
/// Adapter class to convert the matrix into a graph
/// <remarks>we can do without this class but this makes it cleaner</remarks>
/// </summary>
public class Node
{
private static Dictionary<string, Node> TempDic = new Dictionary<string, Node>();
public int X { get; private set; }
public int Y { get; private set; }
public Node Parent { get; set; }
public NodeStatus Status { get; set; }
public int Distance { get; set; }

public char GetValue(char[,] g)
{
if (IsValid(X, Y, g))
{
return g[X, Y];
}
else
{
throw new Exception("Invalid Indicies!");
}
}

{
List<Node> nodes = new List<Node>();
Node n = GetNode(X + 1, Y, g);
if (n != null)
{
}
n = GetNode(X - 1, Y, g);
if (n != null)
{
}
n = GetNode(X, Y + 1, g);
if (n != null)
{
}
n = GetNode(X, Y - 1, g);
if (n != null)
{
}
return nodes;
}

private static bool IsValid(int x, int y, char[,] g)
{
return (x >= 0 && x < g.GetLength(0)) && (y >= 0 && y < g.GetLength(1));

}
public static Node GetNode(int x, int y, char[,] g)
{
if (IsValid(x, y, g))
{
string key = string.Format("{0},{1}", x, y);
if (!TempDic.ContainsKey(key))
{
TempDic[key] = new Node { X = x, Y = y };
}
return TempDic[key];
}
else
{
return null;
}
}

public static void Clear()
{
TempDic.Clear();
}
}

public static List<Node> FindNearest(int x, int y, char[,] g, char t)
{
Node.Clear();
Node s = Node.GetNode(x, y, g);
if (s == null)
{
throw new Exception("Invalid indicies");
}
Queue<Node> q = new Queue<Node>();
q.Enqueue(s);
int dist = -1;
List<Node> nodes = new List<Node>();
while (q.Count > 0)
{
Node c = q.Dequeue();
c.Status = NodeStatus.Processed;
{
{
}
}

if (c.GetValue(g) == t)
{
if ((dist == -1 || dist >= c.Distance) && !nodes.Contains(c))
{
dist = c.Distance;
}
}
}

foreach (var n in nodes)
{
Console.WriteLine();
string key = string.Format("{0},{1}", n.X, n.Y);
Console.WriteLine("To :"+key + " Distance:"+n.Distance);
PrintPath(n);
}
return nodes;
}

public static void PrintPath(Node n)
{
if (n == null)
return;
PrintPath(n.Parent);
string key = string.Format("{0},{1}", n.X, n.Y);
Console.WriteLine(key);
}``````

``````char[,] g = new char[,]
{
{'w', 'w', 'e', 'w', 'd' },
{'w', 'w', 'e', 'w', 'd' },
{'w', 'w', 'd', 'w', 'd' }
};
.FindNearest(0, 0, g, 'd');``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

Java solution :

//Algo:
1st part: Use BFS to find the distance from the input random coordinate to the nearest door.
2nd part: Insert all the door coordinates with distance 0 into the queue. Now run BFS.
We are doing this because we want the distance to be updated from all directions. Spreading the gossip from all sources. :)
Maintain a third 2D array which will hold the distances. Then return this distance array.

``````import java.io.*;
import java.util.*;

class Coordinate {
int x,y;
Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
}

class Array {
public static final int grid[][] = {
{2, 1, 2, 1, 2, 2, 2},
{2, 0, 2, 0, 0, 0, 2},
{2, 0, 0, 0, 2, 0, 2},
{2, 2, 0, 2, 0, 0, 2},
{2, 0, 0, 0, 0, 0, 2},
{2, 2, 2, 0, 0, 0, 2},
{2, 2, 2, 2, 2, 2, 2}};

static final int moves[][] = {{1,0,-1,0},
{0,1,0,-1}};

public static void main (String[] args) {
System.out.print(getMinDist(grid,2,3));
}

static int getMinDist(int grid[][], int m, int n) {
if(grid[m][n] == 2)
return -1;

if(grid[m][n] == 1)
return 0;

int visited[][] = new int[grid.length][grid.length];

int dist = getMinDistUtil(grid,m,n,visited);
return dist;
}

static int getMinDistUtil(int grid[][], int m, int n, int visited[][]) {

visited[m][n] = 1;

// get neighbors and add to queue if valid
while(!queue.isEmpty()) {

Coordinate coor = queue.poll();

int dist = visited[coor.x][coor.y];
System.out.println("dist : " + dist + " x,y " + coor.x + "," + coor.y);

if(grid[coor.x][coor.y] == 1)
return (dist - 1);

for(int i=0; i<moves.length; i++) {
int X = coor.x + moves[i];
int Y = coor.y + moves[i];
System.out.println("X,Y : " + X + "," + Y);
if(X >= 0 && X < grid.length &&
Y >= 0 && Y < grid.length &&
grid[X][Y] != 2 && visited[X][Y] == 0)
{
visited[X][Y] = dist + 1;
}
}
}

return -1;
}
}``````

Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.