I spent several hours on ACing this question in Scala
scala\n  def firstDayBeenInAllRooms(nvs: Array[Int]): Int = {\n\n    val len = nvs.length\n    import scala.collection.mutable.HashMap\n    val tab = new HashMa
```scala\n  def firstDayBeenInAllRooms(nvs: Array[Int]): Int = {\n\n    val len = nvs.length\n    import scala.collection.mutable.HashMap\n    val tab = new HashMap[Int, Long]\n    val mod = 1000000007L\n   \n    def f(idx: Int): Long = {\n  \n\n      if (idx == 0) return 0L\n      if (tab.contains(idx)) return tab(idx)\n      if (nvs(idx - 1) == idx - 1) {\n        tab.put(idx,  f(idx - 1) + 2)\n      } else {\n        tab.put(idx, ((f(idx - 1) + f(idx - 1)) + 2L - f(nvs(idx - 1)) + mod) % mod)\n      }\n\n      tab(idx)\n    }\n\n    (f(len - 1) % mod).toInt\n  }\n```
[]