Facebook Interview Question for Software Engineer / Developers


Country: United States




Comment hidden because of low score. Click to expand.
4
of 6 vote

FloodFill(Pixel p, Color curr, Color new)
{
if Color(p) != curr then return
Q.Add(p); // Q is a queue that stores pixels
while Q is not empty do
{
p = Q.getFirst();
if Color(p) == curr then set color(p) = new;
Q.Add(p.rightPixel());
Q.Add(p.leftPixel());
Q.Add(p.topPixel());
Q.Add(p.bottomPixel());
}
return;
}

- William Borges September 26, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Put a condition check while adding left, right, top and bottom pixels to the queue. Otherwise the algorithm is going to have NO exit condition and its gonna run infinite.

- KB August 14, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

Java implementation. No need for "visited" set because when we color a pixel with the new color we know we've already visited it.

private static void fill(int r, int c, int newColor, int[][] mat) {
    int rows = mat.length;
    if (rows == 0) {
        return;
    }
    int cols = mat[0].length;

    int oldColor = mat[r][c];
    if (oldColor == newColor) {
        return;
    }

    Queue<Integer> queue = new ArrayDeque<>();
    queue.add(r * cols + c);

    while (!queue.isEmpty()) {
        int pos = queue.poll();
        int currR = pos / cols;
        int currC = pos % cols;

        if (mat[currR][currC] != oldColor) {
            continue;
        }

        mat[currR][currC] = newColor;
        if (currC > 0)
            queue.add(currR * cols + currC - 1);
        if (currC < cols - 1)
            queue.add(currR * cols + currC + 1);
        if (currR > 0)
            queue.add((currR - 1) * cols + currC);
        if (currR < rows - 1)
            queue.add((currR + 1) * cols + currC);
    }
}

- Safi December 12, 2014 | 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