Understanding the Logic.
There are 2 key points that help us solve this question.\n1. The first time you reach room i, it will always be from position i-1.\nFrom position i-1, you can e
There are 2 key points that help us solve this question.\n**1. The first time you reach room *i*, it will always be from position *i-1.***\nFrom position *i-1*, you can either go to *i* or *nextVisit[i-1]* but *nextVisit[i-1] <= i-1* as given in the problem statement. Thus, to go ahead, you visit *i-1* again if number of visits are not even and then visit *i*  for the first time.\n\n**2. The first time you reach room *i*, all previous room will have been visited even number of times.**\nTo  move to room i, i-1 must have been visited even number of times, subsequently to have visited i-1, i-2 must have been visited even number of times and so on.\n\nThus, we can break down the process of reaching room *i* into these sub-problems.\n**1. Reach to room *i-1* for the first time.**\nWe can maintain a dp of length of n where:\n*n is total number of rooms (length of input array).*\n*dp[i] = Number of days after which we reach room **i** for the first time.*\nThus, to reach room *i-1*, we take dp[i-1] days.\n**2. Add one day and move to *nextVisit[i-1]***\nWhen we first visited *nextVisit[i-1]* it was on odd count, same as now, thus it can be considered as pseudo-first visit.\n**3. Move from *nextVisit[i-1]*  to *i-1***\nSince our visit to *nextVisit[i-1]* can be considered as pseudo-first visit, we can directly calculate the number of days it takes from *nextVisit[i-1]*  to *i-1* as *dp[i-1] - dp[nextVisit[i-1]]*.\n**4. Add one day to go from [i-1] to i**\n\nThus we can say *dp[i] = dp[i-1] (Step 1) + 1 (Step 2) + dp[i-1] - dp[nextVisit[i-1]](Step 3) + 1(Step 4)*.\nor ```dp[i] = dp[i-1] * 2 - dp[nextVisit[i-1]] + 2```\n\n*Note: dp[0] will always be 0 because we start from there.*\n\nSample Code (Java): \n```\nclass Solution {\n    int mod = (int)1e9 + 7;\n    public int firstDayBeenInAllRooms(int[] nextVisit) {\n        long[] dp = new long[nextVisit.length];\n        for(int i = 1; i < nextVisit.length; i++) \n            dp[i] = (dp[i-1] * 2 - dp[nextVisit[i-1]] + 2 + mod) % mod;\n        return (int)dp[dp.length - 1];\n    }\n}\n```\n\nWhy do we add *mod*? Value goes out of Integer range making it reach the negative end on some testcases, we bring it back to range by adding mod and then we perform modulo operation to get our number of days.\nBut why does it not affect the value, we\'re adding *mod* right? It should change the actual value we get....right?\nActually, no.\nModulo operator has this property, (a+b) % c = ((a%c) + (b%c)) % c\nthus (x + mod) % mod = (x%mod + mod%mod)%mod = x%mod as mod%mod = 0.\n\n
[]