Welcome back to CodeYourCraft! Today, we're diving into an exciting topic - Data Structures and Algorithms. Specifically, we'll focus on a problem called Reconstruct Itinerary.
This lesson is designed for both beginners and intermediate learners, so let's start with the basics!
š” Data Structures are specialized formats for organizing, storing, and managing data. They help in efficient data retrieval and manipulation.
Algorithms, on the other hand, are step-by-step procedures to solve a problem. In programming, we use algorithms to perform tasks efficiently.
The Reconstruct Itinerary problem is about creating a valid itinerary from a list of flight bookings. It's a great example of using graph algorithms to solve a real-world problem!
Let's take a look at a sample input:
["AXH ABO", "OBI AXH", "AXH BQR", "BQR OBI", "OBI AXH"]
Each pair represents a flight from city A to city B. The goal is to reconstruct the itinerary in a way that all flights can be taken in sequence.
Let's see some code!
# Python code for Reconstruct Itinerary
# Define the function
def reconstruct_itinerary(flights):
# Create a dictionary to store flights
flights_dict = {}
# Loop through all flights
for flight in flights:
# Split the flight string
city_from, city_to = flight.split(' ')
# If the city is not in the dictionary, add it
if city_from not in flights_dict:
flights_dict[city_from] = []
# Add the flight to the list of flights for the city
flights_dict[city_from].append(city_to)
# Sort the flights by departure cities
flights_dict = {k: sorted(v) for k, v in sorted(flights_dict.items())}
# Initialize the itinerary
itinerary = []
# Start with the first city and traverse through all flights
for city in flights_dict:
for flight in flights_dict[city]:
# Check if the itinerary is valid (last city matches the start of the next flight)
if itinerary and itinerary[-1] == flight:
itinerary.append(flight)
# If the itinerary is not valid, break and continue with the next city
else:
break
# Reverse the itinerary to match the expected order
itinerary.reverse()
return itinerary
# Test the function
flights = ["AXH ABO", "OBI AXH", "AXH BQR", "BQR OBI", "OBI AXH"]
print(reconstruct_itinerary(flights))What is the output of the above code for the given flights list?
Now you've learned the Reconstruct Itinerary problem and have seen a practical implementation in Python! As you practice more, you'll become more comfortable with data structures and algorithms. Happy coding! š”š