Facebook Interview Question
SDE1sCountry: United States
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]
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();
}
}
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:
- Matviy Ilyashenko November 14, 2017