Amazon Interview Question for SDE-3s


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);

- Anonymous March 11, 2017 | Flag Reply
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.

- elkon March 13, 2017 | Flag Reply
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!");
            }
        }


        public List<Node> AdjNodes(char[,] g)
        {
            List<Node> nodes = new List<Node>();
            Node n = GetNode(X + 1, Y, g);
            if (n != null)
            {
                nodes.Add(n);
            }
            n = GetNode(X - 1, Y, g);
            if (n != null)
            {
                nodes.Add(n);
            }
            n = GetNode(X, Y + 1, g);
            if (n != null)
            {
                nodes.Add(n);
            }
            n = GetNode(X, Y - 1, g);
            if (n != null)
            {
                nodes.Add(n);
            }
            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;
                foreach (var adjNode in c.AdjNodes(g))
                {
                    if (adjNode.Status == NodeStatus.Undiscovered)
                    {
                        q.Enqueue(adjNode);
                        adjNode.Parent = c;
                        adjNode.Distance = c.Distance + 1;
                    }
                }

                if (c.GetValue(g) == t)
                {
                    if ((dist == -1 || dist >= c.Distance) && !nodes.Contains(c))
                    {
                        nodes.Add(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');

- fa1987 March 18, 2017 | Flag Reply


Add a Comment
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.

Learn More

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.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More