Problem solution · Java

Check If Digits Are Equal in String After Operations I

Check If Digits Are Equal in String After Operations I: a Java solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Direct simulation
Source
walkccc LeetCode Solutions
Length
53 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

Direct simulation

For Check If Digits Are Equal in String After Operations I, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. Return the accumulated state once all relevant input has been handled.

Code notes

  • 53 lines of Java from the credited upstream file 3461.java.
  • The implementation visibly relies on sequence storage.
  • 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeCheck If Digits Are Equal in String After Operations I · JavaJava
Use this to learn the idea, then write your own version.
class Solution {  public boolean hasSameDigits(String s) {    final int n = s.length();    int num1 = 0;    int num2 = 0;     for (int i = 0; i + 1 < n; ++i) {      final int coefficient = nCMOD10(n - 2, i);      num1 += (coefficient * (s.charAt(i) - '0')) % 10;      num1 %= 10;      num2 += (coefficient * (s.charAt(i + 1) - '0')) % 10;      num2 %= 10;    }     return num1 == num2;  }   // Returns (n, k) % 10.  private int nCMOD10(int n, int k) {    final int mod2 = lucasTheorem(n, k, 2);    final int mod5 = lucasTheorem(n, k, 5);    int[][] lookup = {        {0, 6, 2, 8, 4}, // mod2 == 0        {5, 1, 7, 3, 9}  // mod2 == 1    };    return lookup[mod2][mod5];  }   // Returns (n, k) % prime.  private int lucasTheorem(int n, int k, int prime) {    int res = 1;    while (n > 0 || k > 0) {      final int nMod = n % prime;      final int MOD = k % prime;      res *= nCk(nMod, MOD);      res %= prime;      n /= prime;      k /= prime;    }    return res;  }   // Returns (n, k).  private int nCk(int n, int k) {    int res = 1;    for (int i = 0; i < k; ++i) {      res *= (n - i);      res /= (i + 1);    }    return res;  }} 

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 ↗