Skip to content

Commit 92007b3

Browse files
Added solution for max length substring
1 parent 9a42dc8 commit 92007b3

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,8 @@ Happy to accept any contributions to this in any langugage.
5252
17. [Leet Code 554 Brick Wall](https://leetcode.com/problems/brick-wall/) | [Solution 1](./level_medium/LeetCode_554_Brick_Wall_Medium.ts)
5353
18. [Leet Code 1190 Reverse Substrings Between Each Pair of Paranthesis](https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/) | [Solution 1](level_medium/LeetCode_1190_Reverse_Substrings.ts) | [Solution Optimized](level_medium/LeetCode_1190_Reverse_Substrings_1.ts)
5454
19. [Leet Code 22 Generate Paranthesis](https://leetcode.com/problems/generate-parentheses/) | [Solution Brute Force](level_medium/LeetCode_22_Generate_Paranthesis_1.ts) | [Solution BF Optimized](level_medium/LeetCode_22_Generate_Paranthesis_2.ts)
55-
20. [Leet Code 54 Spiral Matrix] | [Solution](./med/../level_medium/SpiralMatrix.ts)
55+
20. [Leet Code 54 Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) | [Solution](./med/../level_medium/SpiralMatrix.ts)
56+
21. [Leet Code 1239 - Maximum length of the unique character string](https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/) | [Solution](./level_medium/LeetCode_1239_MaxLength.ts)
5657

5758

5859
## Hard
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* Problem: Leet Code 1239
3+
* Solution uses a backtracking approach to make all the possible combinations or sets of the input string.
4+
* With that, we calculate that there are unique characters and should we backtrack. If not, the entire string
5+
* is created recursively keeping track of the maximum length.
6+
*
7+
* @param arr
8+
*/
9+
function maxLength(arr: string[]): number {
10+
return backTrackHelper("", arr, 0)
11+
};
12+
13+
function backTrackHelper(str: string, arr: string[], idx: number): number {
14+
15+
if (idx >= arr.length) {
16+
return str.length;
17+
}
18+
19+
const newStr = str + arr[idx]
20+
let maxLengthWithInclusion = 0;
21+
if (isUnique(newStr)) {
22+
maxLengthWithInclusion = backTrackHelper(newStr, arr, idx + 1);
23+
}
24+
25+
return Math.max(maxLengthWithInclusion, backTrackHelper(str, arr, idx + 1));
26+
}
27+
28+
// Using the frequency counter for each character to see if we have any duplicates.
29+
function isUnique(str: string) {
30+
31+
const chars: boolean[] = Array(26).fill(false);
32+
for (let idx = 0; idx < str.length; idx++) {
33+
const charCode = str.charCodeAt(idx) - 97;
34+
if (chars[charCode] === true) return false;
35+
chars[charCode] = true;
36+
}
37+
38+
return true;
39+
}

0 commit comments

Comments
 (0)