diff --git a/posts/algorithms/leetcode-daily.html b/posts/algorithms/leetcode-daily.html index 04e9789..afe7d93 100644 --- a/posts/algorithms/leetcode-daily.html +++ b/posts/algorithms/leetcode-daily.html @@ -35,6 +35,45 @@

Leetcode Daily

+

+ count good numbers + — 13/13/24 +

+
+

understanding the problem

+

+ p is a combinatoric problem at heart. You have some slots for + evens and some for primes, with a limited number of choices for + each. Leverage the multiplication rule, which states that if you + have \(n\) slots with \(x\) choices, you get \(x^n\) possible + outcomes. +

+

doing it

+

+ So, what's the answer? If we know which slots we have and the + number of choices for them, we're done. Since this is leetcode, + they don't let you think—they just give you the answer. You + have 2 types of slots (even and odd indices) with 5 + (\(\{0,2,4,6,8\}\)) and 4 (\(\{2,3,5,7\}\)) choices respectively. + Therefore, the answer is: \(5^{\text{# even slots}}\cdot4^{\text{# + odd slots}}\) By counting or with small cases, we have + \(\lceil\frac{n}{2}\rceil\) even slots and + \(\lfloor\frac{n}{2}\rfloor\) odd slots. Let's submit it! +

+

+ And.... TLE. Checking everything when you submit your + code—in this case, constraint \(n\leq 10^{16}\) informs us + of something suspect. In the worst case, \(\frac{n}{2}\approx + n^14\). This is far too many multiplications, so we can leverage + binary exponentiation instead (and probably should've been the + whole time!). Don't forget the mod. +

+
+

solution: rephrase the question

Definitionally, you remove the last duplicate. If such - duplicate is at 0-indexed i, it belongs to the \(\lceil - \frac{i + 1}{3}\rceil\)th chunk of 3 (i.e. operation). Find the last - duplicate by leveraging a frequency map and iterating backwards - through the input. + duplicate is at 0-indexed i, it belongs to the + \(\lceil \frac{i + 1}{3}\rceil\)th chunk of 3 (i.e. operation). + Find the last duplicate by leveraging a frequency map and + iterating backwards through the input.

asymptotic complexity

diff --git a/public/code/algorithms/leetcode-daily/cgn.cpp b/public/code/algorithms/leetcode-daily/cgn.cpp new file mode 100644 index 0000000..4237eec --- /dev/null +++ b/public/code/algorithms/leetcode-daily/cgn.cpp @@ -0,0 +1,19 @@ +class Solution { +public: + static constexpr long long MOD = 1e9 + 7; + long long mpow(long long a, long long b, long long mod=MOD) { + long long ans = 1; + while (b > 0) { + if (b & 1) { + ans = (ans * a) % MOD; + } + a = (a * a) % MOD; + b >>= 1; + } + return ans; + } + int countGoodNumbers(long long n) { + long long even_slots = (n + 1) / 2, odd_slots = n / 2; + return (mpow(5, even_slots) * mpow(4, odd_slots)) % MOD; + } +};