Order people to maximize happiness from standing before their idol
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Cognition's online assessment, last asked Oct 2024. It tests graphs, functional graphs and cycles.
There are n people, numbered from 0. Each person i has an idol idol[i], someone else in the group, and earns happiness[i] if they stand somewhere to the left of their idol in the line (not necessarily next to them). Return an order of all n people that makes the total happiness as large as possible.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
best_order(idol: list[int], happiness: list[int]) -> list[int]— returns a permutation of0..n-1, leftmost person first. Any optimal order is accepted.
Example
idol = [1, 2, 0, 0, 3]
happiness = [5, 2, 4, 3, 1]
best_order(idol, happiness) -> [2, 4, 3, 0, 1] # total 13
People 0, 1 and 2 form a cycle (0 -> 1 -> 2 -> 0), so one of them must stand right of their idol. Giving up person 1 (happiness 2) is cheapest: 15 - 2 = 13. In the order above, 2 is left of 0, 4 is left of 3, 3 is left of 0 and 0 is left of 1.
Constraints
-
2 <= n <= 10^5;idol[i] != i;1 <= happiness[i] <= 10^9.
Clarifying questions
- Does "before their idol" mean anywhere to the left, or immediately to the left?
- Can two people share an idol? Can someone idolize themselves?
- Can happiness be zero or negative?
- Should the function return the order, the total, or both?
What a strong answer covers
- Model it as a functional graph: an edge from each person to their idol. Every component has exactly one cycle with trees hanging into it.
- Every person off a cycle can be satisfied; on each cycle at least one person can't, and dropping exactly one edge per cycle leaves a forest that can all be satisfied. So the best total is the sum of happiness minus the smallest happiness on each cycle.
- Find cycles with iterative coloring (or by peeling in-degree-0 nodes), drop the cheapest edge on each, then output a topological order of the remaining edges (person before idol) with Kahn's algorithm.
- O(n) time and memory; no recursion so 10^5 people don't overflow the stack.
- Test against brute force over all permutations for small
n.
Follow-ups
- Happiness counts only when the person stands immediately left of their idol.
- Each person may have several idols, each with its own happiness. Why does this become much harder?
- Return the maximum total only, with O(1) extra memory beyond the input.
Where it's asked
- Cognition · Online assessment · Last asked Oct 2024Timed online coding assessment
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
