WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Dynamic Programming · Expert · question 80 of 100

Solve the problem of finding the Maximum Length of a Concatenated String with Unique Characters using dynamic programming.?

📕 Buy this interview preparation book: 100 Dynamic Programming questions & answers — PDF + EPUB for $5

The problem can be defined as follows: Given an array of strings ‘arr‘, find the maximum length of a concatenated string of unique characters that can be formed by taking any combination of strings from ‘arr‘.

To solve this problem using dynamic programming, we can use a 1D array ‘dp[i]‘ to represent the maximum length of a concatenated string of unique characters that can be formed using the first ‘i‘ strings in ‘arr‘.

The base case is ‘dp[0] = 0‘, since we cannot form a concatenated string of unique characters using an empty array.

For each ‘dp[i]‘, we need to consider two cases: either we include the ‘i‘th string from ‘arr‘, or we don’t include it.

If we don’t include the ‘i‘th string, then ‘dp[i]‘ is simply equal to ‘dp[i-1]‘.

If we do include the ‘i‘th string, we need to check whether the characters in the ‘i‘th string are unique when combined with the characters in the previous strings. We can use a hashset to keep track of the characters we have seen so far. If any character in the ‘i‘th string is already in the hashset, we cannot use the ‘i‘th string and ‘dp[i]‘ is equal to ‘dp[i-1]‘. If all characters in the ‘i‘th string are unique, we can add the length of the ‘i‘th string to ‘dp[i-1]‘ to get ‘dp[i]‘.

The final answer is ‘dp[n]‘, where ‘n‘ is the length of ‘arr‘.

Here’s the Java code to implement the dynamic programming solution:

public int maxLength(List<String> arr) {
    int n = arr.size();
    int[] dp = new int[n+1];
    dp[0] = 0;
    for (int i = 1; i <= n; i++) {
        String s = arr.get(i-1);
        boolean unique = true;
        Set<Character> seen = new HashSet<>();
        for (char c : s.toCharArray()) {
            if (seen.contains(c)) {
                unique = false;
                break;
            }
            seen.add(c);
        }
        if (unique) {
            dp[i] = dp[i-1] + s.length();
        } else {
            dp[i] = dp[i-1];
        }
    }
    return dp[n];
}

For example, if ‘arr = ["un", "iq", "ue"]‘, the expected output is ‘4‘, since the maximum length of a concatenated string of unique characters is ‘"uniq"` or ‘"ique"`. The dynamic programming solution gives the correct output.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Dynamic Programming interview — then scores it.
📞 Practice Dynamic Programming — free 15 min
📕 Buy this interview preparation book: 100 Dynamic Programming questions & answers — PDF + EPUB for $5

All 100 Dynamic Programming questions · All topics