|
| 1 | +/** |
| 2 | + * Letter Combinations of a Phone Number problem |
| 3 | + * The algorithm determines the final size of the return array (combs) and allocates |
| 4 | + * corresponding letter for each element, assuming that the return array is alphabetically sorted. |
| 5 | + * It does so by running two loops for each letter: |
| 6 | + * - the first loop determines the starting positions of the sequence of subsequent letter positions |
| 7 | + * - the second loop determines the length of each subsequent sequence for each letter |
| 8 | + * The size and space complexity are both O("size of final array"), as even though there are 4 loops, |
| 9 | + * each element in the final array is accessed only once. |
| 10 | + */ |
| 11 | + |
| 12 | +#include <stdlib.h> // for the malloc() function |
| 13 | +#include <string.h> // for the strlen() function |
| 14 | + |
| 15 | +char *get_letters(char digit) { |
| 16 | + switch (digit) { |
| 17 | + case '2': |
| 18 | + return "abc"; |
| 19 | + case '3': |
| 20 | + return "def"; |
| 21 | + case '4': |
| 22 | + return "ghi"; |
| 23 | + case '5': |
| 24 | + return "jkl"; |
| 25 | + case '6': |
| 26 | + return "mno"; |
| 27 | + case '7': |
| 28 | + return "pqrs"; |
| 29 | + case '8': |
| 30 | + return "tuv"; |
| 31 | + case '9': |
| 32 | + return "wxyz"; |
| 33 | + default: |
| 34 | + return ""; |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +char **letterCombinations(char *digits, int *return_size) { |
| 39 | + char *cp; |
| 40 | + int i, j, k, l, ind, k_tot, l_tot, digits_size = 0; |
| 41 | + |
| 42 | + if (*digits == '\0') { |
| 43 | + *return_size = 0; |
| 44 | + return NULL; |
| 45 | + } |
| 46 | + |
| 47 | + *return_size = 1; |
| 48 | + cp = digits; |
| 49 | + while (*cp != '\0') { |
| 50 | + *return_size *= strlen(get_letters(*cp)); |
| 51 | + digits_size++; |
| 52 | + cp++; |
| 53 | + } |
| 54 | + |
| 55 | + char **combs = malloc(sizeof(char*) * (*return_size)); |
| 56 | + for (i = 0; i < *return_size; i++) { |
| 57 | + combs[i] = malloc(sizeof(char) * (digits_size + 1)); |
| 58 | + combs[i][digits_size] = '\0'; |
| 59 | + } |
| 60 | + |
| 61 | + k_tot = 1; |
| 62 | + l_tot = (*return_size); |
| 63 | + for (i = 0; i < digits_size; i++) { // loop accross digits |
| 64 | + cp = get_letters(digits[i]); |
| 65 | + l_tot /= strlen(cp); |
| 66 | + for (j = 0; j < strlen(cp); j++) { // loop accross letters of the digit |
| 67 | + for (k = 0; k < k_tot; k++) { // loop across the subset starting positions for each letter |
| 68 | + for (l = 0; l < l_tot; l++) { // loop accross each subset positions for each letter |
| 69 | + ind = k * l_tot * strlen(cp) + l + l_tot * j; |
| 70 | + combs[ind][i] = cp[j]; |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + k_tot *= strlen(cp); |
| 75 | + } |
| 76 | + |
| 77 | + return combs; |
| 78 | +} |
0 commit comments