## Facebook Interview Question for SDE1s

• 0

Country: United States

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

We can just run DFS on a graph and check if vertices were already visited. If some vertex was already visited:
1) There is cycle in graph
2) Remove edge that make us a cycle (end with this visited vertex)
Because we visit each vertex only once, time complexity O(N), because we use hash to store visited vertices - space complexity is also O(N) (actually because we use recursion, it will always create extra variables on each level of recursion, so space complexity always not less then recursion depth, that can be also up to N in this case)
Code:

static class DirectedGraphNode {
int label;
List<DirectedGraphNode> neighbors;

DirectedGraphNode(int x) {
label = x;
neighbors = new ArrayList<>();
}

List<Integer> getNeighborsLabels() {
List<Integer> labels = new ArrayList<Integer>();
for(DirectedGraphNode neighbor : neighbors)
return labels;
}
}

private static boolean removeCycles(DirectedGraphNode node, Set<Integer> visited) {
boolean isCycle=false;
Iterator<DirectedGraphNode> it=node.neighbors.iterator();
while(it.hasNext()) {
DirectedGraphNode neighbour = it.next();
if(visited.contains(neighbour.label)) {
isCycle=true;
it.remove();
} else {
isCycle|=removeCycles(neighbour, visited);
}
}
visited.remove(node.label);
return isCycle;
}

private static void doTest1Yes() {
DirectedGraphNode nodes[] = new DirectedGraphNode[3];
for(int i=0;i<3;i++)
nodes[i]=new DirectedGraphNode(i);

System.out.println(removeCycles(nodes[0], new HashSet<Integer>())?"YES":"NO");
for(int i=0;i<3;i++)
System.out.println("Node "+i+": "+nodes[i].getNeighborsLabels());
}

private static void doTest2No() {
DirectedGraphNode nodes[] = new DirectedGraphNode[5];
for(int i=0;i<5;i++)
nodes[i]=new DirectedGraphNode(i);

System.out.println(removeCycles(nodes[0], new HashSet<Integer>())?"YES":"NO");
for(int i=0;i<5;i++)
System.out.println("Node "+i+": "+nodes[i].getNeighborsLabels());
}

private static void doTest3No() {
DirectedGraphNode nodes[] = new DirectedGraphNode[4];
for(int i=0;i<4;i++)
nodes[i]=new DirectedGraphNode(i);

System.out.println(removeCycles(nodes[0], new HashSet<Integer>())?"YES":"NO");
for(int i=0;i<4;i++)
System.out.println("Node "+i+": "+nodes[i].getNeighborsLabels());
}

private static void doTest4Yes() {
DirectedGraphNode nodes[] = new DirectedGraphNode[4];
for(int i=0;i<4;i++)
nodes[i]=new DirectedGraphNode(i);

System.out.println(removeCycles(nodes[0], new HashSet<Integer>())?"YES":"NO");
for(int i=0;i<4;i++)
System.out.println("Node "+i+": "+nodes[i].getNeighborsLabels());
}

public static void main(String[] args) {
doTest1Yes();
doTest2No();
doTest3No();
doTest4Yes();
}
}

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

Simple and Straightforward python solution using DFS search

def removeCycle(graph):

def dfs(graph, visited, vertex):

if visited[vertex]==2:
return
visited[vertex]=1

for neigbhours in graph[vertex]:
if visited[neigbhours]==1:
print('Deleting edge from {} to {}'.format(vertex,neigbhours))
graph[vertex] = list(set(graph[vertex])-set([neigbhours]))
elif visited[neigbhours]==0:
dfs(graph, visited, neigbhours)
else:
print('Graph already processed through this vertex')

visited[vertex]=2

# Visited 0 -> Not visited yet, 1-> Under process, 2-> DFS completed
visited = [0 for _ in range(len(graph)+1)]

for vertex in graph.keys():
if visited[vertex]==0:
dfs(graph, visited, vertex)

# Check if the cycles has been removed or not
print(' New Graph(without cycles)')
for key, items in graph.iteritems():
print(key,items)
return

def main():

# removeCycle in a DirectedGraph
graph = dict()
graph[1]=[2]
graph[2]=[4]
graph[3]=[2]
graph[4]=[3]
graph[5]=[2,7]
graph[6]=[5]
graph[7]=[6]

Comment hidden because of low score. Click to expand.
-2
of 2 vote

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
Pattern pattern = Pattern.compile("[74][47]+");
public String macthInteger(String input1[],String input2[]){
long grater=Long.parseLong(input2[0]);
int count=0;
int pointter=0;
boolean flag=false;
for(String jack:input2){
String finaloutput=input1[count];
long val=Long.parseLong(jack);
if(pattern.matcher(jack).matches() && val>=1 && val<=1000000000 && finaloutput.length()>=1 && finaloutput.length()<=10 && Pattern.matches("[a-zA-Z]+", finaloutput) == true){
flag=true;
if(grater>=val){
grater=val;
pointter=count;
}
}
count++;
}

if(flag==true){
return input1[pointter];
}else{
return "-1";
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Long n = in.nextLong();
Solution sol=new Solution();
String output="-1";
String s1="";
String s="";
if(n!=0 && n>=1 && n<=100000){
for(Long a0 = 0l; a0 < n; a0++){
s += in.next()+",";
Long n1 = in.nextLong();
s1+=""+n1+",";
}
if(!s.equals("") || !s1.equals("")){
String in1[]=s.split(",");
String in2[]=s1.split(",");
output=sol.macthInteger(in1,in2);
}
}
System.out.println(output);
in.close();
}
}

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

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.