Learn With Champak · Python DSA lesson

Data Structures vs Algorithms: Three Python Examples from a Railway System

A sorted list helps us find a train, a linked list models changing bookings, and a graph connects stations. Run all three Python programs below.

Core idea: A data structure organizes information; an algorithm specifies steps to process it. The best pairing depends on the operations you need.

EXAMPLE 01

Sorted array + binary search

Find a train quickly

The sorted Python list is the data structure: it holds train names in alphabetical order. Binary search is the algorithm: it compares the target with the middle item and discards half the remaining list at each step.

Try it yourself

  • Run the editor with Shatabdi Express in standard input. The program returns index 3.
  • Try Rajdhani Express or a name absent from the list.
  • Binary search needs sorted data. Its search time is O(log n); maintaining the sorted array after insertions can cost O(n).

Open this program in the full editor ↗

EXAMPLE 02

Linked list + booking operations

Add and cancel records

A linked list stores each booking in a node that points to the next one. The code adds a new booking at the head, traverses the list, and unlinks a matching booking when cancelled.

Try it yourself

  • Run the editor. It books Asha, Ravi and Meena, then cancels Ravi.
  • Adding at the head takes O(1). Finding Ravi by name requires a scan, so cancellation takes O(n).
  • This is a teaching model. A real ticketing system would use unique booking IDs and persistent storage.

Open this program in the full editor ↗

EXAMPLE 03

Graph + shortest path

Choose a route between stations

The graph represents stations as vertices and railway connections as weighted edges. Dijkstra’s algorithm explores routes in order of distance using a priority queue, then returns the shortest path for nonnegative weights.

Try it yourself

  • Run with Varanasi on the first input line and Lucknow on the second.
  • The sample returns Varanasi → Prayagraj → Lucknow, 330 km.
  • The distances are illustrative, not official railway distances or train schedules.

Open this program in the full editor ↗

Compare the three examples

Railway taskData structureAlgorithm or operationKey point
Find a trainSorted list (array)Binary searchFast search when the list is sorted
Change bookingsLinked listAdd, traverse, unlinkHead insertion is fast; name lookup still scans
Find a routeWeighted graphDijkstra’s shortest pathConnections and distances shape the result

Practice: Add one train, cancel a different passenger, and change one route distance. Predict each result before running the code.

Which data structure would you choose for a live train timetable, and why? Share your reasoning in the comments.