Home
Log in
DescriptionSubmissionsSolution
DescriptionSubmissionsSolution
Loading...

Log in to run or submit

words =

Codey

Practise coding problems, test your solutions and track your progress.

Explore

  • Problems
  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

© 2026 Codey. Personal learning project.

Solution
Updated: 2026-02-23

Idea

Derive ordering constraints from adjacent words, then topologically sort characters.

Approach

  • Initialize graph with all unique characters.
  • For each adjacent pair (w1, w2), find first differing char a != b and add edge a -> b.
  • Handle invalid prefix case: if w1 starts with w2 but w1 is longer, return "".
  • Topo sort with Kahn’s algorithm; if cycle, return "".

Why it works

Adjacent-word comparisons provide the minimal necessary constraints; topo sort yields a valid character order iff constraints are acyclic.

Code
Loading...
Complexity
Time: O(totalChars + edges)
Space: O(U + edges)
Solution
Updated: 2026-02-23

Idea

Derive ordering constraints from adjacent words, then topologically sort characters.

Approach

  • Initialize graph with all unique characters.
  • For each adjacent pair (w1, w2), find first differing char a != b and add edge a -> b.
  • Handle invalid prefix case: if w1 starts with w2 but w1 is longer, return "".
  • Topo sort with Kahn’s algorithm; if cycle, return "".

Why it works

Adjacent-word comparisons provide the minimal necessary constraints; topo sort yields a valid character order iff constraints are acyclic.

Code
Loading...
Complexity
Time: O(totalChars + edges)
Space: O(U + edges)