Find minimum number of Substrings with unique characters
Last Updated :
23 Jul, 2025
Given string 's', the task is to divide a given string s into multiple substrings, with each substring containing only unique characters. This means that no character should be repeated within a single substring. The goal is to find the minimum number of such substrings required to satisfy this condition.
Examples:
Input: s = "abacaba"
Output: 4
Explanation: Two possible partitions are ("a", "ba", "cab", "a") and ("ab", "a", "ca", "ba"). It can be shown that 4 is the minimum number of substrings needed.
Input: s = "ssssss"
Output: 6
Explanation: The only valid partition is ("s", "s", "s", "s", "s", "s").
Naive Approach: The basic way to solve the problem follows the below idea:
- We initialize an empty set and iterate through the given string. For each character encountered, we check if it is already present in the set.
- If it is, this means that we need to start a new substring since the current substring has a repeated character. We increase our answer variable and clear the set to start a new substring. We then add the current character to the set.
- After iterating through the entire string, the value of the answer variable gives us the minimum number of substrings required to partition the given string such that each substring has unique characters.
Below is the implementation for the above approach:
C++
// C++ program to Finding minimum number
// of Substrings with unique Characters
#include <bits/stdc++.h>
using namespace std;
// Function to Find Minimum Number of
// Substrings with Unique Characters
int partitionString(string s)
{
// Create an unordered set to
// store unique characters
unordered_set<char> st;
// Initialize the answer
// variable to 1
int ans = 1;
// Iterate through the given string
for (int i = 0; i < s.size(); i++) {
// Check if the current character
// is already present in the set
if (st.find(s[i]) != st.end()) {
// If it is, increment the
// answer variable and clear
// the set to start a
// new substring
ans++;
st.clear();
}
// Add the current character
// to the set
st.insert(s[i]);
}
// Return the answer variable, which
// gives the minimum number
// of substrings required
return ans;
}
// Drivers code
int main()
{
string S = "abacaba";
// Function Call
cout << "Minimum Number of Substrings with Unique "
"Characters: "
<< partitionString(S);
return 0;
}
Java
// Java program to Finding Minimum Number of Substrings with
// Unique Characters
import java.util.*;
// Function to Find Minimum Number of Substrings with Unique
// Characters
class GFG {
static int partitionString(String s)
{
// Create a HashSet to store unique characters
Set<Character> set = new HashSet<>();
// Initialize the answer variable to 1
int ans = 1;
// Iterate through the given string
for (int i = 0; i < s.length(); i++) {
// Check if the current character is already
// present in the set
if (set.contains(s.charAt(i))) {
// If it is, increment the answer variable
// and clear the set to start a new
// substring
ans++;
set.clear();
}
// Add the current character to the set
set.add(s.charAt(i));
}
// Return the answer variable, which gives the
// minimum number of substrings required
return ans;
}
public static void main(String[] args)
{
String S = "abacaba";
System.out.print(partitionString(S));
}
}
// This code is contributed by Ravi Singh
Python3
# Function to Find Minimum Number of
# Substrings with Unique Characters
def partitionString(s):
# Create an unordered set to
# store unique characters
st = set()
# Initialize the answer
# variable to 1
ans = 1
# Iterate through the given string
for i in range(len(s)):
# Check if the current character
# is already present in the set
if s[i] in st:
# If it is, increment the
# answer variable and clear
# the set to start a
# new substring
ans += 1
st.clear()
# Add the current character
# to the set
st.add(s[i])
# Return the answer variable, which
# gives the minimum number
# of substrings required
return ans
# Drivers code
S = "abacaba"
# Function Call
print("Minimum Number of Substrings with Unique Characters:", partitionString(S))
C#
// C# program to Finding Minimum Number of Substrings with
// Unique Characters
using System;
using System.Collections.Generic;
public class GFG {
static int partitionString(string s)
{
// Create a HashSet to store unique characters
HashSet<char> set = new HashSet<char>();
// Initialize the answer variable to 1
int ans = 1;
// Iterate through the given string
for (int i = 0; i < s.Length; i++) {
// Check if the current character is already
// present in the set
if (set.Contains(s[i])) {
// If it is, increment the answer variable
// and clear the set to start a new
// substring
ans++;
set.Clear();
}
// Add the current character to the set
set.Add(s[i]);
}
// Return the answer variable, which gives the
// minimum number of substrings required
return ans;
}
static public void Main()
{
// Code
String S = "abacaba";
Console.Write("Minimum Number of Substrings with Unique Characters: " + partitionString(S));
}
}
// THis code is contributed by karthik
JavaScript
// JavaScript program to Finding minimum number
// of Substrings with unique Characters
// Function to Find Minimum Number of Substrings with Unique
// Characters
function partitionString(s) {
// Create a set to store unique characters
let st = new Set();
// Initialize the answer
// variable to 1
let ans = 1;
// Iterate through the given string
for (let i = 0; i < s.length; i++) {
// Check if the current character
// is already present in the set
if (st.has(s[i])) {
// If it is, increment the
// answer variable and clear
// the set to start a
// new substring
ans++;
st.clear();
}
// Add the current character
// to the set
st.add(s[i]);
}
// Return the answer variable, which
// gives the minimum number
// of substrings required
return ans;
}
// Driver code
let S = "abacaba";
// Function Call
console.log(
"Minimum Number of Substrings with Unique Characters: "
+ partitionString(S));
OutputMinimum Number of Substrings with Unique Characters: 4
Time Complexity: O(n) where n is the length of the input string.
Auxiliary Space: O(n) in the worst case This is because we store each character of the input string in the hash set, and in the worst case, all characters of the string are unique.
Efficient Approach: To solve the problem using a Greedy approach follow the below idea:
To solve this problem, we need to keep track of the last occurrence of each character in the string s. Whenever we encounter a repeated character, we know that the current substring contains a character that is repeated, so we need to start a new substring. We can determine the start of the new substring by setting the value of start to the index of the repeated character. We also increased the value of ans to indicate that we have started a new substring.
Below are the steps for the above approach:
- Create an array list of size 26 to store the last index of each character (initially set to -1).
Initialize the starting index of the current substring to 0. - Initialize the answer variable ans to 1.
- Iterate through the given string s:
- Get the index of the current character in the array by subtracting 'a' from it.
- Check if the current character is already present in the current substring by comparing its last index with the starting index of the current substring.
- If it is, increment the answer variable ans and update the starting index of the new substring to the current index.
- Update the last index of the current character in the array with the current index.
- Return the answer variable ans, which gives the minimum number of substrings required.
Below is the implementation for the above approach:
C++
// C++ program to Finding Minimum
// Number of Substrings with
// Unique Characters
#include <bits/stdc++.h>
using namespace std;
// Function to Find Minimum Number of
// Substrings with Unique characters
int partitionString(string s)
{
// Create an array to store the
// last index of each character
vector<int> last(26, -1);
// Initialize the starting index
// of the current substring to 0
int start = 0;
// Initialize the answer variable to 1
int ans = 1;
// Iterate through the given string
for (int i = 0; i < s.length(); i++) {
// Get the index of the current
// character in the array
int index = s[i] - 'a';
// Check if the current character
// is already present in the
// current substring
if (last[index] >= start) {
// If it is, increment the answer
// variable and update the
// starting index of the
// new substring
ans++;
start = i;
}
// Update the last index
// of the current character
last[index] = i;
}
// Return the answer variable, which
// gives the minimum number of
// substrings required
return ans;
}
// Drivers code
int main()
{
string S = "abacaba";
// Function Call
cout << "Minimum Number of Substrings with Unique "
"Characters: "
<< partitionString(S);
return 0;
}
Java
// Java program to Finding Minimum Number of Substrings with
// Unique Characters
import java.util.*;
// Function to Find Minimum Number of Substrings with Unique
// Characters
class GFG {
static int partitionString(String s)
{
// Create an array to store the last index of each
// character
int[] last = new int[26];
Arrays.fill(last, -1);
// Initialize the starting index of the current
// substring to 0
int start = 0;
// Initialize the answer variable to 1
int ans = 1;
// Iterate through the given string
for (int i = 0; i < s.length(); i++) {
// Get the index of the current character in the
// array
int index = s.charAt(i) - 'a';
// Check if the current character is already
// present in the current substring
if (last[index] >= start) {
// If it is, increment the answer variable
// and update the starting index of the new
// substring
ans++;
start = i;
}
// Update the last index of the current
// character
last[index] = i;
}
// Return the answer variable, which gives the
// minimum number of substrings required
return ans;
}
public static void main(String[] args)
{
String S = "ssssss";
System.out.print(partitionString(S));
}
}
// This code is contributed by Ravi Singh
Python3
# Function to Find Minimum Number of
# Substrings with Unique characters
def partitionString(s):
# Create an array to store the
# last index of each character
last = [-1] * 26
# Initialize the starting index
# of the current substring to 0
start = 0
# Initialize the answer variable to 1
ans = 1
# Iterate through the given string
for i in range(len(s)):
# Get the index of the current
# character in the array
index = ord(s[i]) - ord('a')
# Check if the current character
# is already present in the
# current substring
if last[index] >= start:
# If it is, increment the answer
# variable and update the
# starting index of the
# new substring
ans += 1
start = i
# Update the last index
# of the current character
last[index] = i
# Return the answer variable, which
# gives the minimum number of
# substrings required
return ans
# Drivers code
if __name__ == '__main__':
S = "abacaba"
# Function Call
print("Minimum Number of Substrings with Unique Characters: ", partitionString(S))
C#
using System;
using System.Collections.Generic;
public class Program
{
// Function to find minimum number of substrings with unique characters
public static int PartitionString(string s)
{
// Create a dictionary to store the last index of each character
Dictionary<char, int> last = new Dictionary<char, int>();
// Initialize the starting index of the current substring to 0
int start = 0;
// Initialize the answer variable to 1
int ans = 1;
// Iterate through the given string
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
// Check if the current character is
// already present in the current substring
if (last.ContainsKey(c) && last[c] >= start)
{
// If it is, increment the answer variable and
// update the starting index of the new substring
ans++;
start = i;
}
// Update the last index of the current character
last[c] = i;
}
// Return the answer variable, which gives
// the minimum number of substrings required
return ans;
}
// Driver's code
public static void Main()
{
string S = "abacaba";
// Function call
Console.WriteLine("Minimum Number of Substrings with Unique Characters: " + PartitionString(S));
}
}
// This code is contributed by Prajwal Kandekar
JavaScript
// JavaScript program to Finding Minimum
// Number of Substrings with
// Unique Characters
function partitionString(s) {
// Create an array to store the
// last index of each character
const last = new Array(26).fill(-1);
// Initialize the starting index
// of the current substring to 0
let start = 0;
// Initialize the answer variable to 1
let ans = 1;
// Iterate through the given string
for (let i = 0; i < s.length; i++) {
// Get the index of the current
// character in the array
const index = s.charCodeAt(i) - 97;
// Check if the current character
// is already present in the
// current substring
if (last[index] >= start) {
// If it is, increment the answer
// variable and update the
// starting index of the
// new substring
ans++;
start = i;
}
// Update the last index
// of the current character
last[index] = i;
}
// Return the answer variable, which
// gives the minimum number of
// substrings required
return ans;
}
// Example usage
const S = "abacaba";
console.log(`Minimum Number of Substrings with Unique Characters: ${partitionString(S)}`);
OutputMinimum Number of Substrings with Unique Characters: 4
Time Complexity: O(n) where n is the length of the input string.
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem