Skip to content

Commit 00480b3

Browse files
committed
Add itinerary tickets code
1 parent ea15f2b commit 00480b3

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.thealgorithms.datastructures.hashmap.hashing;
2+
3+
import java.util.HashMap;
4+
5+
/**
6+
* This class represents an itinerary of tickets. Given a list of tickets, it finds the
7+
* complete itinerary.
8+
*/
9+
public class ItineraryTickets {
10+
11+
public static void main(String[] args) {
12+
HashMap<String, String> tickets = new HashMap<>();
13+
tickets.put("Chennai", "Bengaluru");
14+
tickets.put("Mumbai", "Delhi");
15+
tickets.put("Goa", "Chennai");
16+
tickets.put("Delhi", "Goa");
17+
18+
String start = getStart(tickets);
19+
System.out.print(start);
20+
for (String key : tickets.keySet()) {
21+
System.out.print(" -> " + tickets.get(start));
22+
start = tickets.get(start);
23+
}
24+
}
25+
26+
/**
27+
* This method finds the starting point of the itinerary.
28+
*
29+
* @param tickets A map of tickets where the key is the departure point, and the value is the destination.
30+
* @return The starting point of the itinerary.
31+
*/
32+
public static String getStart(HashMap<String, String> tickets) {
33+
HashMap<String, String> revTickets = new HashMap<>();
34+
for (String key : tickets.keySet()) {
35+
revTickets.put(tickets.get(key), key);
36+
}
37+
for (String key : tickets.keySet()) {
38+
if (!revTickets.containsKey(key)) {
39+
return key; // Starting point
40+
}
41+
}
42+
return null;
43+
}
44+
}

0 commit comments

Comments
 (0)