Dynamic Programming & AdvancedAdvanced LevelStudy Time: 30 mins

Travelling Salesperson Algorithm

The Travelling Salesperson Problem (TSP) seeks the minimum weight tour visiting every city node exactly once and returning to the origin city.

Loading visualizer workspace...

Travelling Salesperson Bitmask DP Trace

Sample Input:4 Cities (0, 1, 2, 3) Distance Matrix
Step 1

Start at Origin City 0

Initial state: visited mask = 0001 (City 0 visited), current position = 0.

Mask: 0001 | Current City: 0 | Cost: 0
Bitmask tracks visited city set efficiently.
Step 2

Explore Sub-Paths & Memoize

Recursively branch to unvisited cities (1, 2, 3), memoizing minimum costs for sub-states (mask, city).

Path: 0 -> 1 -> 3 -> 2 -> 0 vs 0 -> 2 -> 3 -> 1 -> 0
Dynamic programming memoization avoids repeating full permutation calculations.
Step 3

Reconstruct Optimal Hamiltonian Cycle

Combine shortest sub-path costs to compute final minimum tour distance returning to City 0.

Optimal Tour Cost: 35 | Tour Path: 0 -> 1 -> 3 -> 2 -> 0
Reduces runtime from O(N!) factorial to O(N² 2ⁿ).

Real-world analogy: Delivery Driver Route

NP-Hard
Hover over items for details

A delivery truck must visit 5 neighborhood addresses and return to the warehouse using the shortest total driving distance.

  • NP-Hard= Exhaustive search requires O(N!) factorial permutations.

Complexity analysis

Scenario Simulator: Dataset Size (N = 500)
Presets:
N = 10N = 10,000
Complexity Curve MapTravelling Salesperson: O(N × W) Memoized Time
Time (t)Size N (500)N = 500O(N²)O(N log N)O(N)O(log N)O(1)Travelling Sales
Time Steps (N=500)

500 steps (Linear)

O(N × W) Memoized Time

Space Footprint

O(N × W) Cache Matrix

Memory growth rate as N expands.

Performance Rank
Efficient Tier

Relative efficiency rating for large N.

OperationTime ComplexitySpace Complexity
Bitmask Dynamic ProgrammingO(N² × 2ᴺ)O(N × 2ᴺ)

Code implementations

function tsp(dist) {
  const n = dist.length;
  const memo = Array.from({ length: 1 << n }, () => new Array(n).fill(-1));
  // bitmask DP solver
}

Real-world applications

Case 01

Logistics Fleet Routing

Calculates optimal package delivery paths for FedEx/UPS.

Case 02

Circuit Board Drilling

Minimizes robotic arm movement across PCB hole coordinates.

Interview questions

Topic Knowledge Test & Assessment

10 Questions Assessment

Tsp Knowledge & Skill Test

Validate your conceptual understanding, operation mechanics, and core concepts of Tsp.