JAVA | O(N) time | O(1) space | With Comments & Image Explanation | Circular Array
\nclass Solution {\n    static int mod = 1000000007;\n    public int countTexts(String pK) {\n        int n = pK.length();\n        int[] dp = new int[5];\n    
```\nclass Solution {\n    static int mod = 1000000007;\n    public int countTexts(String pK) {\n        int n = pK.length();\n        int[] dp = new int[5];\n        // 1 represents number is present previously, unique digit.\n        Arrays.fill(dp,1);\n        for(int i=n-1;i>=0;i--){\n            dp[i%5] = 0;\n            // Range till which dp needs to filled, i.e., \n\t\t\t// For every i we can add dp[i-1],dp[i-2],dp[i-3] to dp[i] and if pK[i] is either 7 or 9 then we can add dp[i-4] also. \t\t\n\t\t\tint max;\n            if(pK.charAt(i)==\'7\' || pK.charAt(i)==\'9\') max = i+4;\n            else max = i+3;\n\t\t\t// If max goes beyond length then iterate till n. \n            if(max>n) max=n;\n            for(int j =i;j<max && pK.charAt(i)==pK.charAt(j);j++){\n\t\t\t // Since array is circular for dp[i], dp[i-1],dp[i-2],dp[i-3] will be dp[i+2],dp[i+3],dp[i+4], hence j+1 while adding.\n                dp[i%5] = (dp[i%5] + dp[(j+1)%5])%mod;\n            }\n        }\n        return dp[0];\n    }\n}\n```\n![image](https://assets.leetcode.com/users/images/895ac456-577d-40fc-bcc1-35b83aa8f813_1651985770.7568316.png)\n\n\n
['Java']