We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Project Euler #79: Passcode derivation
Project Euler #79: Passcode derivation
Sort by
recency
|
11 Discussions
|
Please Login in order to post a comment
C++ Solution
This is how I solve this challenge. I uses a topological sorting approach to recover the shortest possible secret passcode based on the given login attempts. How it works:
Character Set: First, it extracts all unique characters from the login attempts and stores them in the chars set.
Graph Construction: It constructs a directed graph where each character is a node, and there is a directed edge from character a to character b if a comes before b in any login attempt.
In-Degree Calculation: It calculates the in-degree of each node, representing the number of characters that should come before it.
Topological Sorting: It performs a topological sort on the graph. Starting with characters that have an in-degree of zero, it adds them to the result in lexicographically sorted order. It updates in-degrees and continues the process until all characters are processed.
Result and Validity Check: The final result is the lexicographically smallest order of characters that satisfies the given login attempts. It also checks if there is a unique topological order. If any character has a non-zero in-degree at the end, it indicates an issue, and the result is "SMTH WRONG."
This approach ensures that the recovered passcode is the shortest and lexicographically smallest possible, and it handles cases where there is ambiguity or inconsistencies in the login attempts.
I solved this problem using mathematica and graph theory, too bad I can't use it here..
My code is not pretty, but it worked, and despite being O(v^3) where v is the number of distinct characters in the logins, it's fast --- all testcases run in 0.05 s or less.
Solved this problem in O(T log T). For those seeking hints: one can look at this problem as being a graph problem, in which each letter is a Node and "letter X has to occur before letter Y in the passcode" is a directed edge from X to Y. You can then repeatedly take the lexicographically smallest letter with in-degree zero (this will be the next letter in the passcode) and remove it from the graph. If there is no letter with in-degree zero, then something is wrong. By using the right data structures, you can do this in O(E log E) where E is the number of edges in the graph.
Let me know if you solved this problem in a completely different way, I'm curious!