<p>Given a positive integer <code>k</code>, you need to find the <strong>length</strong> of the <strong>smallest</strong> positive integer <code>n</code> such that <code>n</code> is divisible by <code>k</code>, and <code>n</code> only contains the digit <code>1</code>.</p>

<p>Return <em>the <strong>length</strong> of </em><code>n</code>. If there is no such <code>n</code>, return -1.</p>

<p><strong>Note:</strong> <code>n</code> may not fit in a 64-bit signed integer.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> k = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> The smallest answer is n = 1, which has length 1.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> k = 2
<strong>Output:</strong> -1
<strong>Explanation:</strong> There is no such positive integer n divisible by 2.
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> k = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong> The smallest answer is n = 111, which has length 3.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li>
</ul>

class Solution {
public:
    int smallestRepunitDivByK(int k) {
        // 1  % k
        // 10 % k
        // 100 % k
        // 10^3 % k

        // 10^x mod k = (10^{x-1} mod k) * (10 mod k) mod k
    
        vector<bool> vis(k, false);
        int sum = 0;
        int len = 0;
        int i = 1;

        while (!vis[i]) {
            sum = (sum + i) % k;
            ++len;
            if (sum == 0) return len;
            vis[i] = true;
            i = (i * 10) % k;
        }

        int cycle_len = 0;
        int cycle_sum = 0;

        int j = i;

        do {
            cycle_sum = (cycle_sum + j) % k;
            ++cycle_len;
            j = (j * 10)  % k;
        } while (j != i);

        unordered_map<int, int> M;
        M[0] = 0;
        for (int l = 1, cycle_multiple = cycle_sum; M[cycle_multiple] == 0; cycle_multiple = (cycle_multiple + cycle_sum) % k, ++l) {
            M[cycle_multiple] = l;
        }

        int ans = INT_MAX;

        int prefix_cycle_sum = 0;
        for (int l = 0; l <= cycle_len; ++l) {
            if (l > 0) {
                prefix_cycle_sum = (prefix_cycle_sum + j) % k;
                j = (j * 10) % k;
            }
            int need = ((-sum-prefix_cycle_sum) % k + k) % k;
            if (M.count(need)) {
                ans = min(ans, len + l + M[need] * cycle_len);
            }
        }

        return ans == INT_MAX ? -1 : ans;
    }
};
7900