Register for our webinar

How to Nail your next Technical Interview

1 hour
Loading...
1
Enter details
2
Select webinar slot
*Invalid Name
*Invalid Name
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
*All webinar slots are in the Asia/Kolkata timezone
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.
close-icon
Iks white logo

You may be missing out on a 66.5% salary hike*

Nick Camilleri

Head of Career Skills Development & Coaching
*Based on past data of successful IK students
Iks white logo
Help us know you better!

How many years of coding experience do you have?

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Iks white logo

FREE course on 'Sorting Algorithms' by Omkar Deshpande (Stanford PhD, Head of Curriculum, IK)

Thank you! Please check your inbox for the course details.
Oops! Something went wrong while submitting the form.
closeAbout usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar
Our June 2021 cohorts are filling up quickly. Join our free webinar to Uplevel your career
close

Clone Graph Problem

Given A Graph, Build A New One With Reversed Edges

Given a strongly connected directed graph, build a new graph with the same number of nodes but every edge reversed. This is also called transposing a graph.

Example

Input: Any node of this graph:

Output: Any node of the new:

Notes

Input Parameters: Function has one argument pointing to a node of the given graph.

Output: Return any node of the new graph.

Constraints:

● 1

● Value in any node will be a unique integer between 1 and number of nodes, inclusive.

● No multiple edges (connecting any pair of nodes in one direction) or self loops (edges connecting a node with itself) in the input graph.

● You are not allowed to modify the given graph. Return a newly built graph.

Solution

To solve this problem simple DFS will work. We provided one sample solution.

Time Complexity:

Our DFS-like algorithm takes O(n + m) time where n is the number of nodes and m is the number of edges.

Without multiple edges or self loops (which problem statement guarantees) the number of edges m can be as big as n*(n-1) in the worst case. So O(n^2) is the time complexity in terms of n.

Auxiliary Space Used:

O(n) for the call stack used by the recursive function dfs() in the worst case.

Space complexity:

Same O(n + m) or O(n^2) as in Time Complexity. Both input and output graphs take that much space.


// -------- START --------

    /*
    In constraints we are given that each node contains distinct values, so we can keep track of 
    node address using that value. {value : node} 
    */
	static HashMap reversed_graph = new HashMap();

    static void dfs(Node node)
	{        
        // First create new node.
		reversed_graph.put(node.val, new Node(node.val));        
		int n = node.neighbours.size();
        // Visit all the neighbours.
		for (int i = 0; i < n; i++)
		{
            // If node is not visited then first visit it.
			if (reversed_graph.containsKey(node.neighbours.get(i).val) == false )
			{
				dfs(node.neighbours.get(i));
			}
            // Add the reverse edge. 
			reversed_graph.get(node.neighbours.get(i).val).neighbours.add(
                reversed_graph.get(node.val));
		}
	}

	static Node build_other_graph(Node node)
	{
        // Build the graph.
		dfs(node);
        // Return any node of the new graph. 
		return reversed_graph.get(1);
	}

	// -------- END --------

Try yourself in the Editor

Note: Input and Output will already be taken care of.

Clone Graph Problem

Given A Graph, Build A New One With Reversed Edges

Given a strongly connected directed graph, build a new graph with the same number of nodes but every edge reversed. This is also called transposing a graph.

Example

Input: Any node of this graph:

Output: Any node of the new:

Notes

Input Parameters: Function has one argument pointing to a node of the given graph.

Output: Return any node of the new graph.

Constraints:

● 1

● Value in any node will be a unique integer between 1 and number of nodes, inclusive.

● No multiple edges (connecting any pair of nodes in one direction) or self loops (edges connecting a node with itself) in the input graph.

● You are not allowed to modify the given graph. Return a newly built graph.

Solution

To solve this problem simple DFS will work. We provided one sample solution.

Time Complexity:

Our DFS-like algorithm takes O(n + m) time where n is the number of nodes and m is the number of edges.

Without multiple edges or self loops (which problem statement guarantees) the number of edges m can be as big as n*(n-1) in the worst case. So O(n^2) is the time complexity in terms of n.

Auxiliary Space Used:

O(n) for the call stack used by the recursive function dfs() in the worst case.

Space complexity:

Same O(n + m) or O(n^2) as in Time Complexity. Both input and output graphs take that much space.


// -------- START --------

    /*
    In constraints we are given that each node contains distinct values, so we can keep track of 
    node address using that value. {value : node} 
    */
	static HashMap reversed_graph = new HashMap();

    static void dfs(Node node)
	{        
        // First create new node.
		reversed_graph.put(node.val, new Node(node.val));        
		int n = node.neighbours.size();
        // Visit all the neighbours.
		for (int i = 0; i < n; i++)
		{
            // If node is not visited then first visit it.
			if (reversed_graph.containsKey(node.neighbours.get(i).val) == false )
			{
				dfs(node.neighbours.get(i));
			}
            // Add the reverse edge. 
			reversed_graph.get(node.neighbours.get(i).val).neighbours.add(
                reversed_graph.get(node.val));
		}
	}

	static Node build_other_graph(Node node)
	{
        // Build the graph.
		dfs(node);
        // Return any node of the new graph. 
		return reversed_graph.get(1);
	}

	// -------- END --------

Worried About Failing Tech Interviews?

Attend our free webinar to amp up your career and get the salary you deserve.

Ryan-image
Hosted By
Ryan Valles
Founder, Interview Kickstart
blue tick
Accelerate your Interview prep with Tier-1 tech instructors
blue tick
360° courses that have helped 14,000+ tech professionals
blue tick
100% money-back guarantee*
Register for Webinar
All Blog Posts