sorting techniques
data organization
computer science
coding tips
algorithm

How can I order a list of connections

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

A "list of connections" usually means a set of edges such as A -> B, B -> C, C -> D that you want to arrange into path order. That is not a normal sort by one field. It is a graph-ordering problem, and the solution depends on whether the connections form one simple chain, several chains, or a graph with branches and cycles.

Case 1: The Connections Form One Chain

If each connection has a single start and end, and the data represents one continuous path, you can rebuild the ordered list by finding the unique starting node and walking forward.

python
1connections = [("B", "C"), ("A", "B"), ("C", "D")]
2
3next_map = {src: dst for src, dst in connections}
4all_sources = {src for src, _ in connections}
5all_targets = {dst for _, dst in connections}
6start = next(iter(all_sources - all_targets))
7
8ordered = []
9current = start
10while current in next_map:
11    nxt = next_map[current]
12    ordered.append((current, nxt))
13    current = nxt
14
15print(ordered)

This works well when the structure is a simple path with one clear beginning.

Why a Normal Sort Is Not Enough

A regular sort() call compares items independently. It cannot express a rule such as "this pair must come immediately before the pair whose source equals my destination".

That is why the problem feels like sorting but is really about adjacency.

If you only sort lexicographically, you might get this:

python
print(sorted(connections))

That can still be wrong for path order even if it looks neat.

Case 2: Multiple Chains or Branches

If the connections are not a single chain, you need to think in graph terms. You may have:

  • multiple disconnected paths
  • a branching structure where one node points to several others
  • a cycle with no natural start node

In that case, there is no single universal ordered list of edges unless you add more rules.

A useful first step is to compute indegree and outdegree to understand the structure.

python
1from collections import Counter
2
3connections = [("A", "B"), ("B", "C"), ("X", "Y")]
4indegree = Counter(dst for _, dst in connections)
5outdegree = Counter(src for src, _ in connections)
6
7print(indegree)
8print(outdegree)

This tells you whether you have one chain or several disconnected components.

Case 3: You Need Topological Order

If the connections represent prerequisites or dependencies rather than one physical chain, use a topological sort instead of path reconstruction.

python
1from collections import defaultdict, deque
2
3edges = [("compile", "test"), ("test", "deploy"), ("lint", "deploy")]
4
5graph = defaultdict(list)
6indegree = defaultdict(int)
7
8for a, b in edges:
9    graph[a].append(b)
10    indegree[b] += 1
11    indegree.setdefault(a, 0)
12
13queue = deque([node for node, deg in indegree.items() if deg == 0])
14order = []
15
16while queue:
17    node = queue.popleft()
18    order.append(node)
19    for nei in graph[node]:
20        indegree[nei] -= 1
21        if indegree[nei] == 0:
22            queue.append(nei)
23
24print(order)

That solves dependency ordering, not necessarily edge-by-edge chain reconstruction.

Common Pitfalls

  • Treating connection ordering as a normal sort problem when it is actually about graph structure.
  • Assuming there is one valid order even when the data contains branches or multiple disconnected paths.
  • Ignoring cycles, which make simple "find the start and walk" logic fail.
  • Building the forward map without checking whether a source appears more than once.
  • Solving a dependency graph with path logic when a topological sort is what you really need.

Summary

  • Ordering connections depends on the structure behind the data.
  • For one simple chain, find the unique start node and walk through the mapping.
  • For more complex data, inspect indegree, outdegree, and connected components first.
  • Use topological sort when the connections represent dependencies rather than one path.
  • A normal sort is usually the wrong tool unless the connections already contain a sortable sequence field.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.