← Microsoft Interview Insights
My first instinct was to just scan every row and column which is obviously N squared and they were not impressed.
Use a two-pass elimination strategy: first, find a candidate by scanning the matrix and eliminating non-influencers based on follow relationships; then verify the candidate in a second pass. This achieves O(N) time by leveraging the fact that an influencer must follow nobody and be followed by everyone.
Pro tip: Clarify that the matrix is given as a 2D array, so accessing any entry is O(1); the O(N) time refers to the number of matrix accesses, not the input size. Also, mention that the algorithm uses O(1) extra space.
Restate the definition of an influencer: follows nobody (row all false) and is followed by everyone else (column all true except self). Note that there can be at most one influencer.
Initialize candidate = 0. For each i from 1 to N-1, if matrix[candidate][i] is true (candidate follows i), then candidate cannot be the influencer, so set candidate = i. This eliminates one user per check.
Check that the candidate follows nobody: for all j, matrix[candidate][j] is false. Check that everyone else follows the candidate: for all i != candidate, matrix[i][candidate] is true. If both hold, return candidate; else return -1.
Explain that the algorithm performs at most 2N-2 matrix accesses, so O(N) time, and uses only a few variables, so O(1) space.
Consider N=1 (the single user follows nobody and is followed by everyone? By definition, they follow nobody and are followed by everyone else—vacuously true, so return 0). Also, note that if the matrix is not given but can be queried, the same approach works with O(N) queries.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.