Interview Question


Country: United States




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

//I didn't do any input parsing, this is what comes after.
public class Point 
{
	int row;
	int col;
	
	public Point(int r,int c)
	{
		row=r;
		col=c;
	}
	
	public int hashCode()
	{
		int[] vals={row,col};
		return Arrays.hashCode(vals);
	}
	
	public boolean equals(Object obj)
	{
		if(obj==null || !obj instanceof Point)
		{
			return false;
		}
		Point p=(Point)obj;
		return hashCode()==p.hashCode();
	}
}

private void bfs(int[][] m,Point p)
{
	int level=0;
	Deque<Point> q=new LinkedList<Point>();
	HashSet<Point> set=new HashSet<Point>();
	set.add(p);
	q.addFirst(p);
	q.addLast(null);
	while(!q.isEmpty())
	{
		level++;
		while(q.peekFirst()!=null)
		{
			Point curr=q.removeFirst();
			Point[] dirs={new Point(-1,0),new Point(1,0),new Point(0,-1),new Point(0,1)};
			for(Point x:dirs)
			{
				Point next=new Point(curr.row+x.row,curr.col+x.col);
				if(isValid(next,set,matrix) && m[next.row][next.col]>level)
				{
					m[next.row][next.col]=level;
					q.addLast(next);
					
				}
			}
		}
		q.removeFirst();
		q.addLast(null;)
		
	}
	
}

private boolean isValid(Point p, HashSet<Point> set, int[][] m)
{
	return(!set.contains(p) && (p.row>=0 && p.row<m.length) && (p.col>=0 && p.col<m[0].length));
}

public int[][] modifyArray(int[][] matrix)
{
	if(matrix==null||matrix.length==0)
	{
		return null;
	}
	
	ArrayList<Point> ls=getZeros(matrix);
	for(int i=0;i<matrix.length;i++)
	{
		for(int j=0;j<matrix[0].length;j++)
		{
			if(m[i][j]!=0)
			{
				m[i][j]=Integer.MAX_VALUE;
			}
		}
	}
	
	for(Point p:ls)
	{
		bfs(matrix,p);
	}
}

//Time Complexity: O(NMP) where N is number of rows, M is the number of columns and //P is the number positions with zero. Space: O(NM)

- divm01986 July 02, 2016 | 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