#include <stdio.h>
#include <stdlib.h>

#define NO

#ifdef NO
void buildRangeString(int a, int b, char ***list, int *listSize)
{
    char *buffer = malloc(32);
    if (a != b)
        sprintf(buffer, "%d->%d", a, b);
    else
        sprintf(buffer, "%d", a);

    *list = realloc(*list, (*listSize + 1) * sizeof(char *));
    (*list)[*listSize] = buffer;
    *listSize += 1;
}

char **summaryRanges(int *nums, int numsSize, int *returnSize)
{
    *returnSize = 0;
    if (numsSize == 0)
        return NULL;

    char **ss = NULL;
    if (numsSize == 1)
    {
        buildRangeString(*nums, *nums, &ss, returnSize);
        return ss;
    }

    int first = *nums;
    for (int i = 1; i < numsSize; i++)
    {
        if (nums[i - 1] + 1 != nums[i])
        {
            buildRangeString(first, nums[i - 1], &ss, returnSize);
            first = nums[i];
        }
    }
    buildRangeString(first, nums[numsSize - 1], &ss, returnSize);

    return ss;
}
#else
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
#include <string.h>

void buildRangeString(int a, int b, char **list, int *listSize)
{
    char *buffer = calloc(256 * sizeof(char), sizeof(char));
    if (a != b)
        sprintf(buffer, "%d->%d", a, b);
    else
        sprintf(buffer, "%d", a);

    list[*listSize] = buffer;
    *listSize += 1;
}

const char empty[1][0] = {""};
char **summaryRanges(int *nums, int numsSize, int *returnSize)
{
    if (numsSize == 0)
    {
        *returnSize = 0;
        return NULL;
    }

    char **ss = calloc(numsSize * sizeof(char *), sizeof(char *));
    if (numsSize == 1)
    {
        buildRangeString(*nums, *nums, ss, returnSize);
        goto nonull;
    }

    int first = *nums;
    for (int i = 1; i < numsSize; i++)
    {
        if (nums[i] != 1 + nums[i - 1])
        {
            buildRangeString(first, nums[i - 1], ss, returnSize);
            first = nums[i];
        }
    }
    buildRangeString(first, nums[numsSize - 1], ss, returnSize);

nonull:
    char **ret = calloc(numsSize * sizeof(char *), sizeof(char *));
    int j = 0;
    for (int i = 0; i < *returnSize; i++)
    {
        if (ss[i] == NULL)
            continue;
        int len = strlen(ss[i]);
        ret[j] = calloc((len + 1) * sizeof(char), sizeof(char));
        for (int x = 0; x < len; x++)
        {
            ret[j][x] = ss[i][x];
        }
        j++;
    }

    *returnSize = j;
    return ret;
}
#endif
int main()
{
    int a[] = {-2147483648, -2147483647, 2147483647};
    int size = 0;
    char **s = summaryRanges(a, sizeof(a) / sizeof(int), &size);

    for (int i = 0; i < size; i++)
    {
        printf("%s\n", s[i]);
        free(s[i]);
    }

    free(s);
    return 0;
}
