Problem 1420

Abstract / Summary

Build an array so that finding the maximum value requires exactly k comparisons during a single search.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1420.py

class Solution:
    def numOfArrays(self, n: int, m: int, k: int) -> int:
        modulo = 1_000_000_007

        @cache
        def deeper(pos, high, cost):
            if pos == n:
                return 1 if cost == k else 0

            # append a smaller number (choose any number from [ 1, high ])
            result = high *   deeper(pos + 1, high, cost)
            # append a new maximum
            if cost < k:
                for i in range(high + 1, m + 1):
                    result += deeper(pos + 1, i,    cost + 1)

            return result % modulo

        return deeper(0, 0, 0)
19 lines | 620 bytes | submitted June 13, 2024 | GitHub   15% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 66% (100k+ submissions).

Typical patterns to solve this problem:
  • Dynamic Programming
  • Prefix Sum
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation computes the number of arrays of length n whose elements are bounded by m, and whose “cost” - defined as the number of times a new maximum appears while scanning the array from left to right - equals k. The result is returned modulo 1 000 000 007. The core of the solution is a depth-first recursion with memoization that explores all possible choices for each position while tracking the current highest value and the accumulated cost.

Key Steps

The entry point creates a constant modulo and defines a cached helper function deeper. The helper receives three parameters: the current index pos, the current maximum value high, and the cost accumulated so far cost.

@cache
def deeper(pos, high, cost):
    if pos == n:
        return 1 if cost == k else 0

When the recursion reaches the end of the array (pos == n), it checks whether the accumulated cost matches the target k. A match contributes one valid array; otherwise it contributes none.

The next part handles the case where the next element does not create a new maximum. Any value from 1 up to the current high can be placed, and the cost remains unchanged. Because there are high such choices, the contribution is expressed as a multiplication rather than an explicit loop.

result = high * deeper(pos + 1, high, cost)

If the current cost is still below the target, the algorithm may also place a value larger than high, thereby raising the maximum and incrementing the cost. This is performed by iterating over all possible new maxima from high + 1 through m.

if cost < k:
    for i in range(high + 1, m + 1):
        result += deeper(pos + 1, i, cost + 1)

Finally, the intermediate sum is reduced modulo the large prime before being returned, ensuring that intermediate values stay within integer limits.

return result % modulo

The public method invokes the helper starting from position 0 with an initial maximum of 0 and zero cost.

return deeper(0, 0, 0)

Edge Cases Handled

When high is zero - which occurs at the very first position - the multiplication high * deeper(...) yields zero, effectively disabling the “append a smaller number” branch because no smaller number exists. The subsequent loop then iterates from 1 to m, guaranteeing that the first element always establishes a new maximum and correctly increments the cost.

If the accumulated cost already equals k, the conditional if cost < k prevents any further increase of the cost, thereby pruning branches that would exceed the target. This ensures that arrays whose cost would overshoot k are not counted.

When pos reaches n before the cost reaches k, the base case returns zero, discarding incomplete cost scenarios. Conversely, if the cost matches k exactly at the final position, the base case returns one, counting the completed array.

The modulo operation applied at each return guarantees that the result remains within the required range even for very large n, m, and k.

Performance Optimizations

The most significant optimization is the use of the @cache decorator, which memoizes the results of deeper for each unique combination of (pos, high, cost). This eliminates redundant recomputation of subproblems that arise from different paths leading to the same state, turning an exponential exploration into a tractable dynamic programming solution.

The multiplication high * deeper(...) replaces an explicit enumeration of all smaller values, reducing the number of recursive calls for that branch from high to a single call. This compact representation cuts down the call overhead and improves cache locality.

By restricting the loop that introduces a new maximum to cases where cost < k, the algorithm avoids unnecessary recursion once the cost budget is exhausted, further limiting the state space explored.

All arithmetic is performed modulo a constant, preventing integer overflow and keeping intermediate results bounded, which contributes to consistent runtime performance across the entire search space.

written by openai gpt

ELI5 - Simplified Explanation

Imagine there is a big bookshelf where you want to line up some blocks. Each block has a number written on it. You have to follow special rules to decide which blocks go in which spot.

The code describes a smart helper who is trying to figure out how many different ways you can fill up the shelf. The helper starts at the very first spot and uses a notebook to keep track of three things. The first thing is which spot is being filled right now. The second thing is the largest number seen on the shelf so far. The third thing is how many times a new biggest number has appeared.

When the helper looks at a spot, there are two ways to choose a block. One way is to pick a number that is not bigger than the largest one already on the shelf, which keeps the current maximum the same. The other way is to pick a number that is even larger than the one before, which makes the maximum jump up and increases the count of big changes.

The helper keeps doing this over and over for every empty spot until the shelf is full. Whenever it reaches the end, it checks if the count of big changes matches the exact amount requested. If it does, that way of filling the shelf is counted as a success. The helper is very clever because it remembers previous answers in its notebook so it does not have to repeat the same work twice. Once every possible combination is checked, the final answer shows the total number of ways to arrange the blocks.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.48 | σ = 1.87

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
fsq C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
varunu28 Java
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
varunu28 Java
wisdompeak C++
22 links | 12 authors | 6 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

7 solutions   June 13, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality