1. Repeated Linear Search for Starting City
Intuition
For each ticket [from, to], check if from appears as a destination in any other ticket by linearly scanning all tickets. The ticket whose departure city never appears as a destination is the starting ticket. Then sequentially match destinations.
Algorithm
- For each ticket
tintickets: - Check if
t.fromis present in any other ticket'stofield. - If not present,
start = t.from. - Reconstruct path by repeatedly scanning tickets for matching departures.
- Return list of cities.
#include <iostream>#include <vector>#include <string> std::vector<std::string> itineraryBrute(const std::vector<std::pair<std::string, std::string>>& tickets) { int n = tickets.size(); std::string start = ""; for (int i = 0; i < n; ++i) { bool isArrival = false; for (int j = 0; j < n; ++j) { if (tickets[i].first == tickets[j].second) { isArrival = true; break; } } if (!isArrival) { start = tickets[i].first; break; } } std::vector<std::string> result = {start}; std::string curr = start; for (int step = 0; step < n; ++step) { for (int i = 0; i < n; ++i) { if (tickets[i].first == curr) { curr = tickets[i].second; result.push_back(curr); break; } } } return result;} int main() { std::vector<std::pair<std::string, std::string>> tickets = { {"Chennai", "Bangalore"}, {"Bombay", "Delhi"}, {"Goa", "Chennai"}, {"Delhi", "Goa"} }; auto res = itineraryBrute(tickets); std::cout << "Itinerary (Brute): "; for (auto& s : res) std::cout << s << " -> "; std::cout << "END"; return 0;}Time & Space Complexity
- Time complexity:
O(N^2) due to quadratic linear searches across all tickets. - Space complexity:
O(N) for the resulting itinerary array.