Oliver and the Game

Pattern: BFS and DFS

medium

Root the tree at the mansion (node 1) and record each node's entry and exit time in one DFS. Node a is an ancestor of b exactly when a's time interval encloses b's. Moving towards the mansion from y finds x when x is an ancestor of y; moving away finds x when x is in y's subtree.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

A city's houses form a tree rooted at the king's mansion, house 1. For each query [type, x, y], Oliver starts at house y: type 0 means he walks towards the mansion, type 1 means he walks away from it (anywhere below y). Return "YES" if he can pass house x (where Bob hides), else "NO". The catalogue has no practice link for this one. The rules here are this guide's statement of the HackerEarth problem.

Think first

  • Walking towards the mansion from y, which houses can he pass?
  • Walking away from it?
  • How can one DFS answer 'is a above b?' in O(1)?

Hints

    Brute force, and why it fails

    For each query, walk up from y (or search below it): O(n) per query.

    The key insight

    Entry and exit times turn every ancestor question into two comparisons.

    Dry run

    Tree rooted at 1: 1-2, 1-3, 2-6, 2-7, 6-9, 7-8, 3-4, 3-5. Query (0, 2, 8): from 8 towards 1, is 2 on the way?

    Step 1 of 3

    The plan

    dfs from 1 recording tin and tout
    anc(a, b) = tin[a] <= tin[b] and tout[b] <= tout[a]
    type 0: anc(x, y); type 1: anc(y, x)
    

    Complexity

    Time
    O(n + q)
    Space
    O(n)

    One DFS and O(1) per query.

    Edge cases

    • x equals y: YES either way.
    • A query on the root.
    • A one-house city.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        private int[] tin, tout;
        private int timer;
    
        public List<String> oliverAndBob(int n, int[][] edges, int[][] queries) {
            List<List<Integer>> adj = new ArrayList<>();
            for (int i = 0; i <= n; i++) adj.add(new ArrayList<>());
            for (int[] e : edges) { adj.get(e[0]).add(e[1]); adj.get(e[1]).add(e[0]); }
            tin = new int[n + 1];
            tout = new int[n + 1];
            timer = 0;
            dfs(1, 0, adj);                         // entry and exit times from the mansion (node 1)
            List<String> out = new ArrayList<>();
            for (int[] q : queries) {
                int x = q[1], y = q[2];
                boolean ok = q[0] == 0 ? isAncestor(x, y) : isAncestor(y, x);   // 0: towards the mansion, 1: away
                out.add(ok ? "YES" : "NO");
            }
            return out;
        }
    
        private boolean isAncestor(int a, int b) {  // a's visit encloses b's visit
            return tin[a] <= tin[b] && tout[b] <= tout[a];
        }
    
        private void dfs(int u, int parent, List<List<Integer>> adj) {
            tin[u] = timer++;
            for (int v : adj.get(u)) if (v != parent) dfs(v, u, adj);
            tout[u] = timer++;
        }
    }

    C++

    class Solution {
    public:
        vector<int> tin, tout;
        int timer;
    
        vector<string> oliverAndBob(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {
            vector<vector<int>> adj(n + 1);
            for (const vector<int>& e : edges) { adj[e[0]].push_back(e[1]); adj[e[1]].push_back(e[0]); }
            tin.assign(n + 1, 0);
            tout.assign(n + 1, 0);
            timer = 0;
            dfs(1, 0, adj);                         // entry and exit times from the mansion (node 1)
            vector<string> out;
            for (const vector<int>& q : queries) {
                int x = q[1], y = q[2];
                bool ok = q[0] == 0 ? isAncestor(x, y) : isAncestor(y, x);   // 0: towards the mansion, 1: away
                out.push_back(ok ? "YES" : "NO");
            }
            return out;
        }
    
        bool isAncestor(int a, int b) {             // a's visit encloses b's visit
            return tin[a] <= tin[b] && tout[b] <= tout[a];
        }
    
        void dfs(int u, int parent, vector<vector<int>>& adj) {
            tin[u] = timer++;
            for (int v : adj[u]) if (v != parent) dfs(v, u, adj);
            tout[u] = timer++;
        }
    };

    Python

    class Solution:
        def oliverAndBob(self, n: int, edges: list[list[int]], queries: list[list[int]]) -> list[str]:
            adj = [[] for _ in range(n + 1)]
            for u, v in edges:
                adj[u].append(v)
                adj[v].append(u)
            tin, tout, timer = [0] * (n + 1), [0] * (n + 1), 0
            stack = [(1, 0, False)]                 # an iterative DFS from the mansion (node 1)
            while stack:
                u, parent, done = stack.pop()
                if done:
                    tout[u] = timer
                    timer += 1
                    continue
                tin[u] = timer
                timer += 1
                stack.append((u, parent, True))
                for v in adj[u]:
                    if v != parent:
                        stack.append((v, u, False))
            anc = lambda a, b: tin[a] <= tin[b] and tout[b] <= tout[a]   # a's visit encloses b's
            return ["YES" if (anc(x, y) if t == 0 else anc(y, x)) else "NO" for t, x, y in queries]   # 0: towards, 1: away

    Common mistakes

    • Mixing up the two query types.
    • Recursing on a deep chain in Python; an explicit stack is safer.

    Similar problems