Official algorithmic problem description and constraints.
You have a string S consisting of lowercase letters. You can perform the following operation on S: Choose two indices i and j , and swap S i β and S j β . For example, if = codechef S=codechef, choosing = 3 i=3 and = 6 j=6 results in the string cohecdef cohecdef. You've always liked unity. To this end, find the minimum number of operations required so that for at least one character that appears in S, all its occurrences form a contiguous segment in S β in short, are united. For example, if = baaba S=baaba, swapping the first and third characters results in aabba S=aabba. All the occurrences of 'b' form a contiguous segment now. Note that the 'a's don't form a contiguous segment, which is fine.
Detailed video explanations, mathematical intuition, and clean C++ implementation code.