# C++ code to find two substrings with one minimal substring

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Suppose we have a lowercase string S with n characters. We have to find two non-empty substrings P and Q, such that −

• Both P and Q are subsequences of S

• For each index i, S[i] belong to exactly one of P and Q.

• P is lexicographically minimum as possible.

So, if the input is like S = "thelightsaber", then the output will be 10, because we need 2 red notebooks, 3 green notebooks, and 5 blue notebooks.

## Steps

To solve this, we will follow these steps −

c := S
sort the array c
a := position of (c[0]) in S
delete c from S
print c[0] and S

## Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
void solve(string S){
string c = S;
sort(c.begin(), c.end());
int a = S.find(c[0]);
S.erase(S.begin() + a);
cout << c[0] << ", " << S << endl;
}
int main(){
string S = "thelightsaber";
solve(S);
}

## Input

"thelightsaber"

## Output

a, thelightsber
Updated on 15-Mar-2022 05:43:29