CodeGround
DashboardProblemsInterviewsAssessmentsCourses
CodeGround
DashboardProblemsInterviewsAssessmentsCourses
The Technical Interview Course

0 of 170 lessons complete

  • Shortest paths when edges have costs
  • When greedy is not allowed
  • Connecting everything cheaply
  • Using every edge exactly once
  • Deriving the graph from the input
  • Retrieval: which graph algorithm?

Advanced Graphs

120 / 170

Advanced Graphs/Lesson 5 of 6·About 61 min

Deriving the graph from the input

The hardest part is not the algorithm. It is working out what the nodes and edges are.

Key idea

The graph is not given

In every problem so far the edges arrived in the input. Some problems instead describe a situation from which the constraints have to be extracted, and once they are, a standard algorithm finishes the job in a few lines.

For those, the work is entirely in the derivation. Writing down what a node is and what an edge means, in words, before any code, is the difference between a short solution and an hour of confusion.

Why it works

Adjacent items give one constraint each

When an ordering must be inferred from a sorted list of items, each adjacent pair yields exactly one piece of information: the position of their first difference tells you which symbol comes before which.

Only the first difference matters. Everything after it is unconstrained, because the earlier position already decided the order. Comparing every pair rather than adjacent ones, or reading past the first difference, both invent constraints that are not there.

1def constraints_from(words):2    pairs = []3    for first, second in zip(words, words[1:]):4        for a, b in zip(first, second):5            if a != b:6                pairs.append((a, b))        # a comes before b7                break                       # nothing after this is implied8    return pairs9 10print(constraints_from(["wrt", "wrf", "er", "ett", "rftt"]))

Edge cases

The invalid case that has no first difference

If one word is a prefix of the next and is longer, such as abc followed by ab, no ordering can produce that. A longer word cannot precede its own prefix.

The loop above walks off the end without appending anything, silently accepting an impossible input. Detecting it needs an explicit check: if no difference was found and the first word is longer, report failure.

This is the single most commonly missed case in this problem, and it is the kind of thing that only appears in the hidden tests.

Key idea

After the derivation, it is a solved problem

Once the constraints are pairs of the form this before that, the rest is the topological ordering from Unit 12, including its cycle detection. Contradictory constraints show up as a cycle and mean no valid order exists.

Remember to include symbols that appear in the input but in no constraint. They can go anywhere, and leaving them out of the node set silently drops them from the answer, which is the isolated-node trap from U12.

Write these down first

What is a node? What does an edge mean, and which direction does it point? Which inputs produce edges, and which produce nothing? What input is impossible, and how would I detect it?

Four sentences. For the problem below they take five minutes and turn it from a hard problem into a derivation followed by an algorithm you have already written.

Find the bug· 5 min

Find the invented constraint

This extracts ordering constraints from adjacent words. It produces constraints that the input does not actually imply. Click the line that is wrong.

Click the line you think is wrong
Complexity· 5 min

Cost of the derivation

Extracting constraints from n words of average length L, then topologically ordering the resulting graph over an alphabet of size a. Give the total time and the space for the graph.

Python
1for first, second in zip(words, words[1:]):2    for a, b in zip(first, second):3        if a != b:4            pairs.append((a, b))5            break
Time
Extra space
Problem· 38 min

Alien Dictionary

Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.

PreviousUsing every edge exactly once
NextRetrieval: which graph algorithm?

0 of 4 parts complete