Some pattern to remember when facing the challenges

=> Remeber this code

    r = l = 0
    res = 0
        for c in s:
            if c == 'L':
                l += 1
            else:
                r += 1
            if r == l:
                res +=1
    return res

```python
#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'substrings' function below.
#
# The function is expected to return an INTEGER.
# The function accepts STRING n as parameter.
#

def substrings(n):
    # Write your code here
    # example: 1379 = [1,3,7,9]
    # 1 = 1*0 + 1 = f(0) + h(0) = f(1)
    # 3 = 1 + (3 + 13) = f(1) + h(1) = f(2)
    # 7 = 1 + 3 + 13 + (7 + 37 + 137) = f(2) + h(2) = f(3)
    # 9 = 1 + 3 + 13 + 7 + 37 + 137 + (9 + 79 + 379 + 1379) = f(3) + h(3) = f(4)
    #
    # ...
    # => f(n) = f(n-1) + h(n)
    # h(2) = 3 + 13 = 16 = 1 * 10 + 3*2
    # h(3) = 7 + 37 + 137 = 181 = 1 * 100+ 3*20 + 7*3 = 10*h(2) + 7*3
    # h(4) =  9 + 39 + 239 + 1239 = 1846 = 1*1000 + 3*200+ 7*30 + 9*4 = 10*h(3) + 9*4
    # Conclucion:
    # => h(n) = 10*h(n-1)+ n*digit[n]
    # => f(n) = f(n-1) + h(n)

    modulo = 10**9 + 7
    fn = hn = 0
    arr = list(map(int, n))
    
    for i in range(0, len(arr)):
        hn = (arr[i]*(i+1) + 10*hn) % modulo
        fn = (fn + hn) % modulo
    
    return fn
    

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = input()

    result = substrings(n)

    fptr.write(str(result) + '\n')

    fptr.close()

```

Overall: Given "1472" calculate the sum of all of its substrings

res = f(n) + h(n)

  • f(n) = f(n-1) + h(n)

  • h(n) = arr[i]*(i+1) + 10*h(n-1)

=> PATTERN: Just remember the code below

for i in range(0, len(arr)):
        hn = arr[i]*(i+1) + 10*hn
        fn = fn + hn

=> Remeber this code

        int res = 0;
        foreach (var num in a)
        {
            res ^= num;
        }

Last updated