Amazon Interview Question for Software Engineers

Country: United States

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

public class Graph<T> {
	Set<Edge<T>> edges;

public class Edge<T> {
	private Vertex<T> end1;
	private Vertex<T> end2;
public class Vertex<T> {
	private T value;
	private List<Edge<T>> connections;
public class CityMerger<T> {
	public void merge(Graph<T> graph, Vertex<T> v1, Vertex<T> v2, T value) {
		Set<Edge<T>> edges = graph.getEdges();
		Iterator<Edge<T>> it = edges.iterator();
		Set<Vertex<T>> uniqueVertices = new HashSet<>();
		while(it.hasNext()) {
			Edge<T> edge =;
			Vertex<T> end2 = edge.getEnd2();
			if(end2.equals(v1) || end2.equals(v2)) {
				edges.remove(edge); // No longer needed as we will create a new Edge to the merged vertex
		// Create a new Vertex
		Vertex<T> mergedVertex = new Vertex<>();
		// Create connections for this
		Iterator<Vertex<T>> itV = uniqueVertices.iterator();
		while(itV.hasNext()) {
			Vertex<T> edge =;
			Edge<T> edgeToMergedVertex = new Edge<>(); // New edge to the merged vertices

- Anonymous February 25, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
of 0 vote

The output doesn't make sense.

Notice that in the input there is no separate entry for 4->6 or 3->4->6....
so 7->6 is not necessary..

These 3 lines are sufficient enough

- ravi March 19, 2016 | Flag Reply

Add a Comment

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.


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


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