AI for travel planning and itineraries in AI for Everyone - Time & Space Complexity
When AI helps plan trips and create travel itineraries, it processes many options and details. Understanding how the time it takes grows as more places or preferences are added is important.
We want to know how the AI's work increases when the trip details get bigger or more complex.
Analyze the time complexity of the following code snippet.
function planItinerary(locations) {
let itinerary = [];
for (let i = 0; i < locations.length; i++) {
for (let j = i + 1; j < locations.length; j++) {
let travelTime = estimateTravelTime(locations[i], locations[j]);
itinerary.push({from: locations[i], to: locations[j], time: travelTime});
}
}
return itinerary;
}
This code creates a list of travel times between every pair of locations to help build a travel plan.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The nested loops that check every pair of locations.
- How many times: For each location, it compares with all following locations, roughly n x (n-1) / 2 times.
As the number of locations grows, the number of pairs grows much faster because each location pairs with many others.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 45 pairs |
| 100 | About 4,950 pairs |
| 1000 | About 499,500 pairs |
Pattern observation: The work grows roughly with the square of the number of locations, so doubling locations makes the work about four times bigger.
Time Complexity: O(n²)
This means if you add more locations, the time to plan grows quickly because the AI checks every pair of places.
[X] Wrong: "Adding one more location only adds a little more work, so time grows linearly."
[OK] Correct: Each new location pairs with all existing ones, so the work grows much faster than just adding one step.
Understanding how AI handles many travel options helps you explain how algorithms scale in real tasks. This skill shows you can think about efficiency, which is valuable in many projects.
"What if the AI only checked travel times from each location to the next one in a list instead of all pairs? How would the time complexity change?"