- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 56 lines of C++ from the credited upstream file 3463.cpp.
- The implementation keeps its working state in language-native values and containers.
- 3 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 4 bool hasSameDigits(const string& s) {5 const int n = s.length();6 int num1 = 0;7 int num2 = 0;8 9 for (int i = 0; i + 1 < n; ++i) {10 const int coefficient = nCkMod10(n - 2, i);11 num1 += (coefficient * (s[i] - '0')) % 10;12 num1 %= 10;13 num2 += (coefficient * (s[i + 1] - '0')) % 10;14 num2 %= 10;15 }16 17 return num1 == num2;18 }19 20 private:21 22 int nCkMod10(int n, int k) {23 const int mod2 = lucasTheorem(n, k, 2);24 const int mod5 = lucasTheorem(n, k, 5);25 static constexpr int lookup[2][5] = {26 {0, 6, 2, 8, 4}, 27 {5, 1, 7, 3, 9} 28 };29 return lookup[mod2][mod5];30 }31 32 33 int lucasTheorem(int n, int k, int prime) {34 int res = 1;35 while (n > 0 || k > 0) {36 const int nMod = n % prime;37 const int kMod = k % prime;38 res *= nCk(nMod, kMod);39 res %= prime;40 n /= prime;41 k /= prime;42 }43 return res;44 }45 46 47 int nCk(int n, int k) {48 int res = 1;49 for (int i = 0; i < k; ++i) {50 res *= (n - i);51 res /= (i + 1);52 }53 return res;54 }55};56