TopCoder problem "IdealString" used in SRM 405 (Division II Level Three)



Problem Statement

    

An ideal string is a string where the 1-based index of the first occurrence of each letter is equal to the number of occurrences of that letter in the string. For example, the "BAOOOA" is an ideal string (quotes for clarity only). The letter 'B' appears 1 time, and its index is 1. The letter 'A' occurs 2 times and its first index is 2. The letter 'O' occurs 3 times and its first index is 3.

Given an int length, return the lexicographically smallest ideal string of that length containing only uppercase letters ('A'-'Z'). If there are no such ideal strings of that length, return an empty String instead.

 

Definition

    
Class:IdealString
Method:construct
Parameters:int
Returns:String
Method signature:String construct(int length)
(be sure your method is public)
    
 

Notes

-String A is lexicographically smaller than string B of the same length if it contains a smaller letter at the first position they differ. Letter X is smaller than letter Y if it comes earlier in the alphabet.
 

Constraints

-length will be between 1 and 100, inclusive.
 

Examples

0)
    
1
Returns: "A"
1)
    
3
Returns: "ABB"
2)
    
2
Returns: ""
There's no way we can construct an ideal string of length 2 - if both its characters are equal, then the number of occurrences (2) and the position of its first occurrence (1) do not match; if they are distinct, then for the second character the number of occurrences (1) and the position of its first occurrence (2) do not match as well.
3)
    
6
Returns: "ABCBCC"
We can permute the last 3 characters in any way, but this way gets us the lexicographically smallest answer.
4)
    
7
Returns: "ABBCCCC"
5)
    
5
Returns: ""

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=9757

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=12177&pm=9757

Writer:

Petr

Testers:

PabloGilberto , Olexiy , Jan_Kuipers , ivan_metelsky

Problem categories:

Greedy, Simple Math, String Manipulation