filmov
tv
LeetCode 1922. Count Good Numbers. Algorithm: Combinatorics. Beats 100% Python3.

Показать описание
Algorithm: Combinatorics with Modular Arithmetic and Modular Exponentiation
The Story: Building Secret Codes
Imagine you're a spy creating secret codes! Your codes are strings of symbols, and you need to make a code that is exactly n symbols long.
You have special rules for building the code:
Rule 1: For the slots at even positions (the 1st slot, 3rd slot, 5th slot, etc. - remember we start counting from 0!), you must use one of the 5 "Even Symbols": maybe Circle, Square, Triangle, Star, or Hexagon.
Rule 2: For the slots at odd positions (the 2nd slot, 4th slot, 6th slot, etc.), you must use one of the 4 "Prime Symbols": maybe Red, Blue, Green, or Yellow.
Your Mission:
Count how many different secret codes you can possibly create that follow Rule 1 and Rule 2. This number can be HUGE, so you just need to give the answer modulo 1,000,000,007 (a special large number spies use).
How to Count the Codes?
Count the Slots: First, determine exactly how many even-positioned slots and how many odd-positioned slots there are in a code of length n.
Count Even Possibilities: Think only about the even slots. You have 5 symbol choices for the first even slot, 5 for the second, and so on.
Count Odd Possibilities: Now think only about the odd slots. You have 4 symbol choices for each.
Combine Them: Since the choices for even slots don't affect the choices for odd slots, * * you can find the total number of different codes by multiplying the even possibilities by the odd possibilities: (Ways to fill Even) * (Ways to fill Odd).
Spy Math (Modulo): Because these numbers get really big, spies use special math. Every time you multiply or calculate a power, you do it "modulo 1,000,000,007" to keep the numbers manageable. There's even a fast trick for calculating large powers like 5 raised to a large number modulo the special number (that's what pow(base, exponent, modulus) does).
Final Answer: The result of that final multiplication (modulo 1,000,000,007) is your answer – the total number of possible secret codes!
Complexity:
Time: O(log n) - Dominated by the pow function calls, which use efficient modular exponentiation (logarithmic time complexity based on the exponent n).
Space: O(1) - Uses a fixed amount of extra space regardless of n (ignoring any internal space used by pow like recursion stack depth, which would be O(log n)).