Pick the shape for the job.
Choose between indexed access, scanning, and building a membership structure.
01 Model the idea
Python lists behave like dynamic arrays of references: indexed access is constant time, appending is amortised constant time, and inserting at the front shifts existing references. Sets and dictionaries use hash tables to support expected constant-time membership or key lookup. Choose based on operations and semantics, not the collection with the fanciest name.
Changing representation must preserve the meaning the problem needs.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
KEEP ordered observations in a sequence
BUILD a set when repeated membership matters
USE an index only when position has meaning03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
tasks = ["Build", "Test", "Review", "Build"]
lookup = set(tasks)
print(tasks[1])
print("Review" in lookup)
print(len(tasks), len(lookup))Test True 4 3
- 1
The list preserves order and duplicates, which can matter to a schedule. The set removes duplicates and is not a positional sequence.
- 2
Building lookup costs work proportional to the input size. It becomes attractive when many membership checks follow.
- 3
If you need a relationship from a name to a record, use a dictionary rather than parallel lists and repeated scans. Be explicit about what happens when keys repeat.
04 Count the cost
O(n) set construction; O(1) indexed access and expected set lookup
O(n) for the lookup set
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Build a name-to-duration lookup from task pairs and retrieve the duration of Test.
Reveal one possible solution +
tasks = [("Build", 40), ("Test", 20)]
lookup = dict(tasks)
print(lookup["Test"])06 Check your reasoning
What is lost when converting a list to a set?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.