~/coding-interview/leetcode-split-string-max-number-unique-substrings.md

Leetcode - Split a String Into the Max Number of Unique Substrings

// TL;DR

Backtracking — try every possible prefix as the next substring, add it to a set if unique, recurse on the remainder. Track the maximum count of unique splits across all paths.

Leetcode - Split a String Into the Max Number of Unique Substrings

Problem Statement

Given a string s, return the maximum number of unique substrings that the given string can be split into.

You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.

A substring is a contiguous sequence of characters within a string.

Example

Input: s = "ababccc"
Output: 5
Explanation: ['a', 'b', 'ab', 'c', 'cc']

Input: s = "aba"
Output: 2
Explanation: ['a', 'ba']
Example 3:

Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.

Solution

Problems like these are solved through recursions, where you want to extract a portion of string and repeat the same algorithm on the rest of string.

Lets look at the algorithm:

  • For checking unique substrings, you need to take a HashSet
  • We would take a substring, check it if its unique.
  • If its unique, we will move forward with rest of string in the same algorithm.

Lets look at one of example:

input=aba

a + (ba)
a + b + (a)
# a is duplicate, it will only (a, b)

Next iteration
ab + (a)

Next Iteration
aba + ()

Code

Lets look at the code:

private int find(String s, Set<String> set) {
  int max = 0;
  for (int i=0; i<s.length(); i++) {
    String sub = s.substring(0, i+1);
    if (!set.contains(sub)) {
      set.add(sub);
      max = Math.max(max, 1 + find(s.substring(i+1), set));
      
      set.remove(sub);
    }
  }
  
  return max;
}

public int maxUniqueSplit(String s) {
  Set<String> set = new HashSet<>();
  return this.find(s, set);
}

Complexity

Its O(n!), factorial of n.

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Leetcode Solution - Best Time to Buy and Sell Stock

Leetcode Solution - Best Time to Buy and Sell Stock

Problem Statement You are given an array prices where prices[i] is the price of…

Binary Tree - Level Order Traversal

Binary Tree - Level Order Traversal

Problem Statement Given a Binary tree, print out nodes in level order traversal…

Four Sum - Leet Code Solution

Four Sum - Leet Code Solution

Problem Statement Given an array nums of n integers and an integer target, are…

Leetcode - Rearrange Spaces Between Words

Leetcode - Rearrange Spaces Between Words

Problem Statement You are given a string text of words that are placed among…

Leetcode - Maximum Non Negative Product in a Matrix

Leetcode - Maximum Non Negative Product in a Matrix

Problem Statement You are given a rows x cols matrix grid. Initially, you are…

Replace all spaces in a string with %20

Replace all spaces in a string with %20

Problem Statement Replace all spaces in a string with ‘%20’ (three characters…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…