You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters.
Return the maximum possible length of s.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: arr = ["un","iq","ue"]
Output: 4
Explanation: All the valid concatenations are:
- ""
- "un"
- "iq"
- "ue"
- "uniq" ("un" + "iq")
- "ique" ("iq" + "ue")
Maximum length is 4.
Example 2:
Input: arr = ["cha","r","act","ers"]
Output: 6
Explanation: Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers").
Example 3:
Input: arr = ["abcdefghijklmnopqrstuvwxyz"] Output: 26 Explanation: The only string in arr has all 26 characters.
Constraints:
1 <= arr.length <= 161 <= arr[i].length <= 26arr[i] contains only lowercase English letters.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.
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.
C++
Java
Python
C#
JavaScript
Time Complexity: O(2^n), where n is the number of strings.
Space Complexity: O(n), for the recursive stack and current string.
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.
This C solution uses bitwise operations to track character inclusion across the 26 possible letters. Recursion explores concatenation options, using the bitmask for collision detection.
C++
Java
Python
C#
JavaScript
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.
| Approach | Complexity |
|---|---|
| Recursive Backtracking with String Set | Time Complexity: O(2^n), where n is the number of strings. |
| Bitmasking for Character Uniqueness Check | Time Complexity: O(2^n), similar to previous approaches for evaluating combinations. |
Longest Consecutive Sequence - Leetcode 128 • NeetCode • 904,041 views views
Watch 9 more video solutions →Practice Maximum Length of a Concatenated String with Unique Characters with our built-in code editor and test cases.
Practice on FleetCode