// 演算法：和 C 版完全一樣，差別只在用 std::unordered_set 取代手寫雜湊表。
// Algorithm: identical to the C version, but using std::unordered_set instead of a
// hand-rolled hash table. Insert every prefix from arr1, then for each y in arr2 walk
// its prefixes from longest to shortest and stop at the first one present in the set.

#include <vector>
#include <unordered_set>
using namespace std;

class Solution {
public:
    int longestCommonPrefix(vector<int>& arr1, vector<int>& arr2) {
        // unordered_set<int>：STL 提供的雜湊集合；insert / count 平均 O(1)。
        // unordered_set<int>: STL hash set with average O(1) insert and lookup.
        unordered_set<int> prefixes;

        // reserve 預先配置桶數，避免插入過程中反覆 rehash，加速約 1.5–2x。
        // Pre-reserve buckets so we don't rehash repeatedly while inserting.
        prefixes.reserve(arr1.size() * 9);

        // range-for + 值複製：x 是 arr1 元素的副本，可以安全修改不影響原陣列。
        // Range-for with a value copy: x is a local copy, safe to mutate.
        for (int x : arr1) {
            while (x > 0) {                  // 枚舉 x 的所有前綴 / enumerate prefixes
                prefixes.insert(x);          // 插入雜湊集合（重複插入不影響）/ idempotent insert
                x /= 10;                     // 砍掉最右一位 / drop rightmost digit
            }
        }

        int best = 0;                        // 目前最佳長度 / best length so far
        for (int y : arr2) {                 // 對 arr2 每個 y / for each y in arr2
            while (y > 0) {                  // 由長到短嘗試 y 的前綴 / longest → shortest
                // count(y) 回傳 0 或 1，表示 y 是否在集合中。
                // count(y) returns 0 or 1, indicating membership.
                if (prefixes.count(y)) {
                    int d = 0;               // 計算 y 的位數 / count digits of y
                    for (int t = y; t > 0; t /= 10) d++;  // 經典數位計數迴圈 / classic loop
                    best = max(best, d);     // 更新最佳 / update best
                    break;                   // 第一次命中即最長 / first hit is longest
                }
                y /= 10;                     // 沒命中，再砍一位 / shorten and retry
            }
        }
        return best;                         // 回傳答案 / return answer
    }
};
