We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • HackerRank Home

    HackerRank

  • |
  • Prepare
  • Certify
  • Compete
  • Hiring developers?
  1. Prepare
  2. Algorithms
  3. Dynamic Programming
  4. String Reduction

String Reduction

Problem
Submissions
Leaderboard
Discussions
Editorial
Topics

Given a string consisting of the letters , and , we can perform the following operation:

  • Take any two adjacent distinct characters and replace them with the third character.

Find the shortest string obtainable through applying this operation repeatedly.

For example, given the string we can reduce it to a character string by replacing with and with : .

Function Description

Complete the stringReduction function in the editor below. It must return an integer that denotes the length of the shortest string obtainable.

stringReduction has the following parameter:
- s: a string

Input Format

The first line contains the number of test cases .

Each of the next lines contains a string to process.

Constraints

Output Format

For each test case, print the length of the resultant minimal string on a new line.

Sample Input

3  
cab  
bcab  
ccccc

Sample Output

2  
1  
5

Explanation

For the first case, there are two solutions: or .
For the second case, one optimal solution is: .
For the third case, no operations can be performed so the answer is .

Author

HackerRank

Difficulty

Hard

Max Score

70

Submitted By

12354

Need Help?


View discussions
View editorial
View top submissions
RESOURCES

  • Dynamic Programming Basics

rate this challenge

MORE DETAILS

Download problem statement
Download sample test cases
Suggest Edits
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy