/*
 * 演算法 / Algorithm:
 * 單次掃描，用 start 記住當前連續區段的起點。 / Single pass; `start` marks the run's start.
 * 當下一個數不等於目前數+1（或到陣列末端）時，區段結束，輸出一個範圍。
 * When the next value breaks the +1 chain (or we hit the end), close the run and emit it.
 */

// LeetCode 要求回傳一個字串陣列，並用 *returnSize 告訴呼叫端共有幾個字串。
// LeetCode wants an array of strings; *returnSize reports how many strings there are.
char** summaryRanges(int* nums, int numsSize, int* returnSize) {
    // 空陣列：沒有任何範圍，回傳數量設為 0，並回傳 NULL。
    // Empty array: zero ranges, set count to 0 and return NULL.
    if (numsSize == 0) {
        *returnSize = 0;          // 告訴呼叫端結果有 0 個 / tell caller there are 0 results
        return NULL;              // 沒有東西可回傳 / nothing to return
    }

    // 最多會有 numsSize 個範圍（每個數字各自成段時）。先配置這麼大的指標陣列。
    // At most numsSize ranges (when no two numbers are consecutive). Allocate that many string pointers.
    // sizeof(char*) 是「一個字串指標」的位元組大小。 / sizeof(char*) = size of one string pointer.
    char** result = (char**)malloc(sizeof(char*) * numsSize);

    int count = 0;                // 目前已產生的範圍數量 / how many ranges produced so far
    int start = 0;                // 當前區段的起點索引 / index where current run starts

    // 逐一檢視每個元素 / examine each element one by one
    for (int i = 0; i < numsSize; i++) {
        // 區段在此結束的條件：i 是最後一個元素，或下一個數不等於目前數 +1。
        // The run ends here if: i is the last element, OR the next value is not (current + 1).
        // 注意用 (long) 轉型避免 nums[i]+1 在 nums[i]==INT_MAX 時溢位。
        // Cast to long so nums[i]+1 won't overflow when nums[i] == INT_MAX.
        if (i == numsSize - 1 || (long)nums[i] + 1 != nums[i + 1]) {
            // 為這個範圍配置字串緩衝區。每個 int 最多 11 字元（含負號），
            // 加上 "->" 與結尾 '\0'，32 位元組綽綽有餘。
            // Allocate a buffer for this range. Each int needs up to 11 chars (with sign);
            // plus "->" and the terminating '\0', 32 bytes is plenty.
            char* buf = (char*)malloc(32);

            if (nums[start] == nums[i]) {
                // 段頭等於段尾 → 單一數字格式 "a"。
                // First equals last → single-number format "a".
                // snprintf 把數字安全地寫進 buf，最多寫 32 位元組。
                // snprintf safely writes the number into buf, at most 32 bytes.
                snprintf(buf, 32, "%d", nums[start]);
            } else {
                // 段頭不等段尾 → 範圍格式 "a->b"。
                // First differs from last → range format "a->b".
                snprintf(buf, 32, "%d->%d", nums[start], nums[i]);
            }

            result[count] = buf;  // 把這個字串存進結果陣列 / store this string in the result
            count++;              // 範圍數量加一 / one more range produced

            start = i + 1;        // 下一段從 i+1 開始 / next run starts at i+1
        }
        // 若條件不成立，代表還在同一段內，什麼都不做，繼續往後走。
        // Otherwise we are still inside the same run; do nothing and continue.
    }

    *returnSize = count;          // 回報實際範圍數量 / report the actual number of ranges
    return result;                // 回傳字串陣列 / return the array of strings
}
