Print the number of nodes in a distributed network
Anonymous User
1147

Very recently in an interview I was asked this question to print the count of nodes in a network of computers. Problem statement : There are nodes/ set of computers( U - V - W - X - Y -Z ) in the range of 1 to a million connected in a network. Each node can talk to its neighbor. All of these nodes will get to execute a class that should be an extension of abstract class with helper methods(more on that below). Now the ask is, when the extension class executes in a node, it should print the number of nodes in the network (just once). Methods guaranteed to have implementations in the abstract class are boolean hasLeft() , boolean hasRight() void sendToLeft(int val) void sendToRight(int val) whereas the public void receiveFromLeft(int val) and public void receiveFromRight(int val) are left abstract. The reecieve methods are only called when sendTo* methods are called from a node left / right to the current node. For instance receivefromRight on a current node will be called when a sendToLeft() is called on a node to the right of the current node and vice- versa.
I was asked to extend / implement the class(This is the code that is technically executed in each node)) and print the number of nodes to a console only once per machine.
This sounded like a distributed computers problem . After the interview, I believe I figured out one way to do this. a) Each node has a book keeping counter variable initialized to 1. Using the helper functions in the parent class, each node decides to send a signal either to left / right / both depending on the location of the node b) update the book keeping counter variable in the current node, when a call is received from left and/or right and pass on the received value(no mutation) to a next left/right neighbor). However the restriction of printing the nodes once / per machine is something I still have to figure it out.
I would like to know the thoughts /suggestions from the community on how one would approach the problem and how can we solve the second piece(printing just once) or can we?

Comments (3)