Bob and Alphabet
Practice
0 (0 votes)
Dynamic programming
Recruit
Medium
Algorithms
Ready
Approved
Problem
19% Success 623 Attempts 30 Points 3s Time Limit 512MB Memory 1024 KB Max Code

Bob has arranged N boxes in a straight line. Each box has a Latin Character \(('a' - 'z')\) written on it. He wants to chain \(26\) boxes in such a way that the chain starts from box with alphabet a and contains all Latin Characters exactly once in increasing lexicographic order, ending at z. In other words, the chain must form the following sequence:
\('abcdefghijklmnopqrstuvwxyz'\)

To join a box \(b_i\) and \(b_j\) with chain, the length of the chain to be used is \(|i - j|\).
Help Bob to minimize the total length of the chain used to make the desired sequence.

Input Format:
First line of input contains of a single integer T - the number of testcases.
Each testcase consists of a single line, which contains a string made up of lowercase Latin Characters - a to z. The string may have one or more occurrences of each character.

Output Format:
For each testcase, print a single integer - the minimum length of chain required to make the required sequence.

Input Constraints:
\(1 \le T \le 10\)
\(26 \le |S| \le 10^6\)
All 26 characters ('a' - 'z') are present in S at least once.

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:30
2 votes
Tags:
AlgorithmsMediumDynamic programming
Points:30
6 votes
Tags:
Dynamic ProgrammingAlgorithmsMediumDynamic programming
Points:30
6 votes
Tags:
AlgorithmsApprovedMediumDynamic programming