Problem solution · Python

Number of Zigzag Arrays III

Number of Zigzag Arrays III: a Python solution using dynamic programming. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Dynamic programming
Source
Kamyu LeetCode Solutions
Length
42 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Dynamic programming

For Number of Zigzag Arrays III, the implementation records answers for smaller states and reuses them to build the requested result without repeating work.

  1. Define precisely what one DP state represents.
  2. Establish the base cases before transitions are evaluated.
  3. Process states in dependency order and combine only already-known values.

Code notes

  • 42 lines of Python from the credited upstream file number-of-zigzag-arrays-iii.py.
  • The implementation visibly relies on cached states.
  • No explicit loop blocks detected.

Complexity

Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeNumber of Zigzag Arrays III · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(n^3)# Space: O(n) # dp, prefix sum, combinatorics, lagrange interpolationclass Solution(object):    def zigZagArrays(self, n, l, r):        """        :type n: int        :type l: int        :type r: int        :rtype: int        """        MOD = 10**9+7        inv, inv_fact = [[1]*2 for _ in xrange(2)]        def inv_factorial(n):            while len(inv) <= n:  # lazy initialization                inv.append(inv[MOD%len(inv)]*(MOD-MOD//len(inv)) % MOD)  # https://cp-algorithms.com/algebra/module-inverse.html                inv_fact.append(inv_fact[-1]*inv[-1] % MOD)            return inv_fact[n]            def f(x):            dp = range(x)            for _ in xrange(n-2):                new_up = [0]*x                for i in xrange(x-1):                    new_up[i+1] = (new_up[i]+dp[~i])%MOD                dp = new_up            return (reduce(lambda accu, x: (accu+x)%MOD, dp, 0)*2)%MOD         m = r-l+1        if m <= n+1:            return f(m)        prefix = [0]*((n+1)+1)        prefix[0] = 1        for i in xrange(len(prefix)-1):            prefix[i+1] = prefix[i]*(m-1-i)%MOD        suffix = [0]*((n+1)+1)        suffix[-1] = 1        for i in reversed(xrange(len(suffix)-1)):            suffix[i] = suffix[i+1]*(m-1-i)%MOD        return reduce(lambda accu, x: (accu+x)%MOD, (f(i+1)*(prefix[i]*suffix[i+1])*(inv_factorial(i)*inv_factorial(n-i)*(-1 if (n-i)%2 else 1)) for i in xrange(n+1)), 0) 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗