Matrix Relations - Google Top Interview Questions


Problem Statement :


You are given an integer n and a two-dimensional list of integers relations. 

You want to fill an n by n matrix using relations, which defines the spatial ordering of some cell values in the matrix. Each element relations[i] contains (x, y, type) which means that

x is left of y if type = 0

x is right of y if type = 1

x is above y if type = 2

x is below y if type = 3

Return the n by n matrix following the constraints in relations. Since some cells may not have a value, 
set it to -1. You can assume each defined cell in the matrix will have a unique value. Also, there is one 
unique solution.



Constraints



n ≤ 500

1 ≤ m ≤ 100,000 where m is the length of relations

Example 1

Input

n = 3

relations = [

    [1, 2, 0],

    [2, 3, 0],

    [1, 2, 2],

    [2, 3, 2]

]

Output

[

    [1, -1, -1],

    [-1, 2, -1],

    [-1, -1, 3]

]

Explanation

The relations says:



1 is left of 2

2 is left of 3

1 is above 2

2 is above 3

Other unfilled squares are set to -1.



Solution :



title-img




                        Solution in C++ :

vector<vector<int>> solve(int n, vector<vector<int>> &relations) {
    unordered_map<int, vector<int>> left, above;
    unordered_map<int, int> indegLeft, indegAbove;
    unordered_map<int, pair<int, int>> mp;
    for (int i = 0; i < relations.size(); i++) {
        int x = relations[i][0], y = relations[i][1], type = relations[i][2];
        mp[x] = {-1, -1};
        mp[y] = {-1, -1};
        if (type == 0 || type == 1) {
            if (type == 1) {
                swap(x, y);
            }
            left[y].push_back(x);
            indegLeft[x]++;
            indegLeft[y] = indegLeft[y];
        } else {
            if (type == 3) {
                swap(x, y);
            }
            above[y].push_back(x);
            indegAbove[x]++;
            indegAbove[y] = indegAbove[y];
        }
    }

    queue<int> q;
    for (auto it = indegLeft.begin(); it != indegLeft.end(); it++) {
        if (it->second == 0) {
            q.push(it->first);
        }
    }

    int j = n - 1;
    while (!q.empty()) {
        int s = q.size();
        while (s--) {
            int p = q.front();
            q.pop();
            mp[p].second = j;
            vector<int> &l = left[p];
            for (int i = 0; i < l.size(); i++) {
                indegLeft[l[i]]--;
                if (indegLeft[l[i]] == 0) {
                    q.push(l[i]);
                }
            }
        }
        j--;
    }

    for (auto it = indegAbove.begin(); it != indegAbove.end(); it++) {
        if (it->second == 0) {
            q.push(it->first);
        }
    }
    int i = n - 1;
    while (!q.empty()) {
        int s = q.size();
        while (s--) {
            int p = q.front();
            q.pop();
            mp[p].first = i;
            vector<int> &l = above[p];
            for (int j = 0; j < l.size(); j++) {
                indegAbove[l[j]]--;
                if (indegAbove[l[j]] == 0) {
                    q.push(l[j]);
                }
            }
        }
        i--;
    }

    vector<vector<int>> res(n, vector<int>(n, -1));
    for (auto it = mp.begin(); it != mp.end(); it++) {
        int val = it->first;
        int x = it->second.first, y = it->second.second;
        res[x][y] = val;
    }
    return res;
}
                    


                        Solution in Java :

import java.util.*;

class Solution {
    public int[][] solve(int n, int[][] r) {
        int[][] ans = new int[n][n];

        // Initialize the matrix
        for (int[] row : ans) {
            Arrays.fill(row, -1);
        }
        Map<Integer, Set<Integer>> downTo = new HashMap<>();
        Map<Integer, Set<Integer>> rightTo = new HashMap<>();
        Map<Integer, Set<Integer>> upTo = new HashMap<>();
        Map<Integer, Set<Integer>> leftTo = new HashMap<>();
        Map<Integer, Integer> xaxis = new HashMap<>();
        Map<Integer, Integer> yaxis = new HashMap<>();

        for (int i = 0; i < r.length; i++) {
            // I change all the right or below direction to left or above

            if (r[i][2] == 1 || r[i][2] == 3) {
                r[i][2]--;
                int tmp = r[i][0];
                r[i][0] = r[i][1];
                r[i][1] = tmp;
            }
            int x = r[i][0];
            int y = r[i][1];

            // Build set if a map doesn't have the key.
            rightTo.computeIfAbsent(x, k -> new HashSet<>());
            rightTo.computeIfAbsent(y, k -> new HashSet<>());
            leftTo.computeIfAbsent(x, k -> new HashSet<>());
            leftTo.computeIfAbsent(y, k -> new HashSet<>());
            downTo.computeIfAbsent(x, k -> new HashSet<>());
            downTo.computeIfAbsent(y, k -> new HashSet<>());
            upTo.computeIfAbsent(x, k -> new HashSet<>());
            upTo.computeIfAbsent(y, k -> new HashSet<>());
            if (r[i][2] == 0) {
                // x left to y
                rightTo.get(x).add(y);
                leftTo.get(y).add(x);
            } else {
                // x up to y
                downTo.get(x).add(y);
                upTo.get(y).add(x);
            }
        }

        Queue<Integer> q = new LinkedList<>();

        // If degree is 0 then we add it to the queue
        for (int k : rightTo.keySet()) {
            if (rightTo.get(k).size() == 0) {
                q.offer(k);
            }
        }
        int idx = n - 1;
        while (!q.isEmpty()) {
            int size = q.size();
            while (size > 0) {
                size--;
                int cur = q.poll();
                // System.out.println(cur);
                yaxis.put(cur, idx);
                for (int p : leftTo.get(cur)) {
                    rightTo.get(p).remove(cur);
                    if (rightTo.get(p).size() == 0) {
                        q.offer(p);
                    }
                }
            }
            idx--;
        }

        q = new LinkedList<>();

        for (int k : downTo.keySet()) {
            if (downTo.get(k).size() == 0) {
                q.offer(k);
            }
        }
        idx = n - 1;
        while (!q.isEmpty()) {
            int size = q.size();
            while (size > 0) {
                size--;
                int cur = q.poll();
                // System.out.println(cur);
                xaxis.put(cur, idx);
                for (int p : upTo.get(cur)) {
                    downTo.get(p).remove(cur);
                    if (downTo.get(p).size() == 0) {
                        q.offer(p);
                    }
                }
            }
            idx--;
        }

        for (int key : xaxis.keySet()) {
            ans[xaxis.get(key)][yaxis.get(key)] = key;
        }

        return ans;
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def solve(self, N, relations):
        rindegree = collections.Counter()
        cindegree = collections.Counter()
        rlist = collections.defaultdict(list)
        clist = collections.defaultdict(list)
        keys = set()

        # Parsing queries
        for x, y, t in relations:
            keys.add(x)
            keys.add(y)

            if t == 0:
                rindegree[y] += 1
                rlist[x].append(y)
            elif t == 1:
                rindegree[x] += 1
                rlist[y].append(x)

            if t == 2:
                cindegree[y] += 1
                clist[x].append(y)
            elif t == 3:
                cindegree[x] += 1
                clist[y].append(x)

        # Get the rows (or cols) mapping of the indegree and list
        def topsort(indegree, elist):
            ans = {}
            q = collections.deque()
            for x in keys:
                if indegree[x] == 0:
                    q.append((x, 0))

            while len(q) > 0:
                index, d = q.popleft()
                ans[index] = d

                for v in elist[index]:
                    if indegree[v] > 0:
                        indegree[v] -= 1
                        if indegree[v] == 0:
                            q.append((v, d + 1))
            return ans

        rans = topsort(rindegree, rlist)
        cans = topsort(cindegree, clist)

        ans = [[-1] * N for _ in range(N)]

        for x in keys:
            ans[cans[x]][rans[x]] = x

        return ans
                    


View More Similar Problems

Reverse a linked list

Given the pointer to the head node of a linked list, change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty. Example: head references the list 1->2->3->Null. Manipulate the next pointers of each node in place and return head, now referencing the head of the list 3->2->1->Null. Function Descriptio

View Solution →

Compare two linked lists

You’re given the pointer to the head nodes of two linked lists. Compare the data in the nodes of the linked lists to check if they are equal. If all data attributes are equal and the lists are the same length, return 1. Otherwise, return 0. Example: list1=1->2->3->Null list2=1->2->3->4->Null The two lists have equal data attributes for the first 3 nodes. list2 is longer, though, so the lis

View Solution →

Merge two sorted linked lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the heads of two sorted linked lists, merge them into a single, sorted linked list. Either head pointer may be null meaning that the corresponding list is empty. Example headA refers to 1 -> 3 -> 7 -> NULL headB refers to 1 -> 2 -> NULL The new list is 1 -> 1 -> 2 -> 3 -> 7 -> NULL. Function Description C

View Solution →

Get Node Value

This challenge is part of a tutorial track by MyCodeSchool Given a pointer to the head of a linked list and a specific position, determine the data value at that position. Count backwards from the tail node. The tail is at postion 0, its parent is at 1 and so on. Example head refers to 3 -> 2 -> 1 -> 0 -> NULL positionFromTail = 2 Each of the data values matches its distance from the t

View Solution →

Delete duplicate-value nodes from a sorted linked list

This challenge is part of a tutorial track by MyCodeSchool You are given the pointer to the head node of a sorted linked list, where the data in the nodes is in ascending order. Delete nodes and return a sorted list with each distinct value in the original list. The given head pointer may be null indicating that the list is empty. Example head refers to the first node in the list 1 -> 2 -

View Solution →

Cycle Detection

A linked list is said to contain a cycle if any node is visited more than once while traversing the list. Given a pointer to the head of a linked list, determine if it contains a cycle. If it does, return 1. Otherwise, return 0. Example head refers 1 -> 2 -> 3 -> NUL The numbers shown are the node numbers, not their data values. There is no cycle in this list so return 0. head refer

View Solution →