Scala Solution Memory and Space Beats 100%
Intuition\nModified BFS\n\n# Approach\n1. For each node use bfs calculate distance of that node from each node\n2. Update Result Array \n\n- Space complexity:\n
# Intuition\nModified BFS\n\n# Approach\n1. For each node use bfs calculate distance of that node from each node\n2. Update Result Array \n\n- Space complexity:\nO(n)\n\n# Code\n```\nimport scala.collection.mutable.Queue\n\nobject Solution {\n\n   def addNeighbourstoQueue(source:Int,qu:Queue[Int],dist:Array[Int],n:Int): (Queue[Int], Array[Int])={\n    if((source + 1) < n && dist(source+1) == -1) {\n       qu.enqueue(source + 1)\n       dist(source +1) = dist(source) + 1\n    }\n    if((source - 1) >= 0 && dist(source-1) == -1) {\n       qu.enqueue(source - 1)\n       dist(source-1) = dist(source) + 1\n    }\n    return (qu, dist)\n  }\n\n    def bfs(source: Int, x: Int, y: Int, n:Int,result: Array[Int]): Array[Int] = {\n      var qu: Queue[Int] = Queue.empty\n      var dist = Array.fill(n)(-1)\n      qu.enqueue(source)\n      dist(source)= 0\n\n      while(qu.nonEmpty){\n        val ele = qu.dequeue()\n        if(x != y){ \n            if(x == ele && dist(y) == -1) {\n                qu.enqueue(y)\n                dist(y) = dist(ele) + 1\n            }\n            else if(y == ele && dist(x) == -1) {\n                qu.enqueue(x)\n                dist(x) = dist(ele) + 1\n        }\n      }\n        var k = addNeighbourstoQueue(ele,qu,dist,n) \n        qu = k._1\n        dist = k._2\n      }\n\n      for(i <- 0 until n){\n        if(dist(i) != 0) {\n           result(dist(i)-1) = result(dist(i)-1) + 1\n        }\n      }\n      result\n    }\n\n    def countOfPairs(n: Int, x: Int, y: Int): Array[Int] = {\n      var result = Array.fill(n)(0)\n      for(i <- 0 until n) {\n        result = bfs(i,x-1,y-1,n,result)\n      }\n      return result\n    }\n}\n```
['Scala']