diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/ItineraryTickets.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/ItineraryTickets.java new file mode 100644 index 000000000000..3e57475ac445 --- /dev/null +++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/ItineraryTickets.java @@ -0,0 +1,31 @@ +package com.thealgorithms.datastructures.hashmap.hashing; + +import java.util.HashMap; + +/** + * This class represents an itinerary of tickets. Given a list of tickets, it finds the + * complete itinerary. + */ +public final class ItineraryTickets { + private ItineraryTickets() { + } + + /** + * This method finds the starting point of the itinerary. + * + * @param tickets A map of tickets where the key is the departure point, and the value is the destination. + * @return The starting point of the itinerary. + */ + public static String getStart(final HashMap tickets) { + HashMap revTickets = new HashMap<>(); + for (String key : tickets.keySet()) { + revTickets.put(tickets.get(key), key); + } + for (String key : tickets.keySet()) { + if (!revTickets.containsKey(key)) { + return key; // Starting point + } + } + return null; + } +} diff --git a/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/ItineraryTicketsTest.java b/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/ItineraryTicketsTest.java new file mode 100644 index 000000000000..5137d9ac606b --- /dev/null +++ b/src/test/java/com/thealgorithms/datastructures/hashmap/hashing/ItineraryTicketsTest.java @@ -0,0 +1,42 @@ +package com.thealgorithms.datastructures.hashmap.hashing; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.util.HashMap; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class ItineraryTicketsTest { + + private HashMap tickets; + + @BeforeEach + public void setUp() { + tickets = new HashMap<>(); + tickets.put("Chennai", "Bengaluru"); + tickets.put("Mumbai", "Delhi"); + tickets.put("Goa", "Chennai"); + tickets.put("Delhi", "Goa"); + } + + @Test + public void testGetStart() { + String start = ItineraryTickets.getStart(tickets); + assertEquals("Mumbai", start); + } + + @Test + public void testGetStartEmptyInput() { + HashMap emptyTickets = new HashMap<>(); + String start = ItineraryTickets.getStart(emptyTickets); + assertNull(start); + } + + @Test + public void testGetStartCircularItinerary() { + tickets.put("Bengaluru", "Mumbai"); + String start = ItineraryTickets.getStart(tickets); + assertNull(start); + } +}