From 66fbabec99dd26463f434da9187a437ccff2858e Mon Sep 17 00:00:00 2001 From: Samuel Ortion Date: Sat, 1 Mar 2025 11:28:44 +0100 Subject: [PATCH] Solve 38. Count and Say --- 38.count-and-say.org | 104 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 38.count-and-say.org diff --git a/38.count-and-say.org b/38.count-and-say.org new file mode 100644 index 0000000..d916eb1 --- /dev/null +++ b/38.count-and-say.org @@ -0,0 +1,104 @@ +#+title: 38. Count And Say +#+author: Samuel Ortion +#+date: <2025-03-01 Sat> + +* Subject + +The count-and-say sequence is a sequence of digit strings defined by the recursive formula: + + countAndSay(1) = "1" + countAndSay(n) is the run-length encoding of countAndSay(n - 1). + +Run-length encoding (RLE) is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string "3322251" we replace "33" with "23", replace "222" with "32", replace "5" with "15" and replace "1" with "11". Thus the compressed string becomes "23321511". + +Given a positive integer n, return the nth element of the count-and-say sequence. + + + +Example 1: + +Input: n = 4 + +Output: "1211" + +Explanation: + +countAndSay(1) = "1" +countAndSay(2) = RLE of "1" = "11" +countAndSay(3) = RLE of "11" = "21" +countAndSay(4) = RLE of "21" = "1211" + +Example 2: + +Input: n = 1 + +Output: "1" + +Explanation: + +This is the base case. + + + +Constraints: + + 1 <= n <= 30 + + +Follow up: Could you solve it iteratively? + + +* Solution + +#+begin_src C +#include +#include +#include + +char *runLengthEncoding(char *message) { + // Realloc to two times the message size, + // as in the worst case scenario, + // the encoding occupies twice as much memory as the message + size_t len = strlen(message); + char *encoding = malloc((2 * len + 1) * sizeof(char)); + int cursor = 0; + int i = 0; + + while (i < len) { + char letter = message[i]; + int count = 0; + while (i < len && message[i] == letter) { + count++; + i++; + } + encoding[cursor] = count + '0'; + encoding[cursor+1] = letter; + cursor += 2; + } + encoding[cursor] = '\0'; + return encoding; +} + +char* countAndSay(int n) { + char *term = malloc(2 * sizeof(char)); + term[0] = '1'; + term[1] = '\0'; + for (int i=1; i < n; i++) { + char *next = runLengthEncoding(term); + free(term); + term = next; + } + return term; +} + +int main() { + printf("%s\n", countAndSay(2)); + printf("%s\n", countAndSay(3)); + printf("%s\n", countAndSay(4)); +} +#+end_src + +#+RESULTS: +| 11 | +| 21 | +| 1211 |