Skip to content

Commit bff74e8

Browse files
Add implementation for itinerary reconstruction from tickets using HashMap
1 parent 4184325 commit bff74e8

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import java.util.HashMap;
2+
3+
public class ItineraryFromTTickets {
4+
public static void main(String[] args) {
5+
HashMap<String, String> tickets = new HashMap<>();
6+
tickets.put("Chennai", "Bangalore");
7+
tickets.put("Mumbai", "Delhi");
8+
tickets.put("Goa", "Chennai");
9+
tickets.put("Delhi", "Goa");
10+
11+
findItinerary(tickets);
12+
}
13+
14+
public static void findItinerary(HashMap<String, String> ticket) {
15+
HashMap<String, String> reverseMap = new HashMap<>();
16+
17+
// step 1 reverse map
18+
for (String from : ticket.keySet()) {
19+
String to = ticket.get(from);
20+
reverseMap.put(to, from);
21+
}
22+
23+
// find the starting city
24+
String start = "";
25+
for (String from : ticket.keySet()) {
26+
if (!reverseMap.containsKey(from)) {
27+
start = from;
28+
break;
29+
}
30+
}
31+
32+
System.out.print("Itinerary: ");
33+
while (ticket.containsKey(start)) {
34+
System.out.print(start + " → ");
35+
start = ticket.get(start);
36+
}
37+
System.out.println(start);
38+
}
39+
40+
}

Hashing/Question/UnionOfTwoArrays.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
//it meanse the two array there is some value after completed the operation the output is : 1,2,3,4,5,6,10 (// ignore the same value )
12

23
import java.util.HashSet;
34

0 commit comments

Comments
 (0)