Problem:
Given an array of strings arr. String s is a concatenation of a sub-sequence of arr which have unique characters.
Return the maximum possible length of s
Examples:
Input: arr = ["un","iq","ue"]
Output: 4
Explanation: All possible concatenations are "","un","iq","ue","uniq" and "ique".
Maximum length is 4.
Input: arr = ["cha","r","act","ers"]
Output: 6
Explanation: Possible solutions are "chaers" and "acters".
My solution:
var maxLength = function(arr) {
if(!arr || arr.length === 0) return 0;
let word = "";
arr.sort((a,b) => b.length - a.length);
let set = new Set();
const removeFromSet = (str) => {
for(let i=0; i<str.length; i++) {
set.delete(str[i]);
}
}
const isInSet = (str) => {
for(let i=0; i<str.length; i++) {
if(set.has(str[i])) {
removeFromSet(str.substring(0, i));
return true;
}
else
set.add(str[i]);
}
return false
}
for(let i=0; i<arr.length; i++) {
if(!isInSet(arr[i])) {
word += arr[i];
}
}
return word.length;
};
It fails for the input: ["ab","cd","cde","cdef","efg","fgh","abxyz"]
It should return 11, but my solution returns 9.
I know that my solution is calculating: "abxyzcdef" and it should be: "abxyzfghcde". Does anyone know what I am doing wrong?
Thanks