




Sponsored
Sponsored
This approach uses a recursive backtracking strategy, where we build each possible concatenated string by considering elements one by one. We use a set to track characters for uniqueness and maximize the length only if all characters are unique.
Time Complexity: O(2^n), where n is the number of strings.
Space Complexity: O(n), for the recursive stack and current string.
1#include <stdio.h>
2#include <stdbool.h>
3#include <string.h>
4
5int maxLengthHelper(char **arr, int index, int size, char *current) {
6    // Check if current string has all unique characters
7    int count[26] = {0};
8    for (int i = 0; current[i] != '\0'; i++) {
9        if (count[current[i] - 'a']++ > 0) {
10            return 0;
11        }
12    }
13    // Try every string from the current index onwards
14    int maxLength = strlen(current);
15    for (int i = index; i < size; i++) {
16        char newCurrent[26 * size + 1];
17        strcpy(newCurrent, current);
18        strcat(newCurrent, arr[i]);
19        int length = maxLengthHelper(arr, i + 1, size, newCurrent);
20        if (length > maxLength) {
21            maxLength = length;
22        }
23    }
24    return maxLength;
25}
26
27int maxLength(char **arr, int arrSize) {
28    char current[1] = "";
29    return maxLengthHelper(arr, 0, arrSize, current);
30}
31
32int main() {
33    char *arr[] = {"un", "iq", "ue"};
34    int size = sizeof(arr) / sizeof(arr[0]);
35    printf("%d\n", maxLength(arr, size));
36    return 0;
37}This C solution uses a recursive helper function to concatenate strings from the array while ensuring all characters are unique, tracked using a count array.
This approach utilizes bitmasking to efficiently determine if characters are unique when combining strings. Each character is represented by a distinct position in a 32-bit integer, allowing for quick checks and updates.
Time Complexity: O(2^n), similar to previous approaches for evaluating combinations.
Space Complexity: O(n), due to the recursive stack with depth dependent on input size.
This JavaScript implementation uses bit shifting to quickly confirm character uniqueness across combinations, efficiently managing potential concats.