Construct Square

Description:

Given a string consisting of lowercase English letters, find the largest square which can be obtained by reordering its characters and replacing them with digits (leading zeros are not allowed) where same characters always map to the same digits and different characters always map to different digits.

If there is no solution, return -1.

Example

  • For s = "ab", the output should be
    constructSquare(s) = 81;
  • For s = "zzz", the output should be
    constructSquare(s) = -1.

    There are no 3-digit square numbers with identical digits.

  • For s = "aba", the output should be
    constructSquare(s) = 900.

    It can be obtained after reordering the initial string into "baa".

Input/Output

  • [time limit] 3000ms (cs)
  • [input] string s

    Constraints:
    2 ≤ s.length < 10.

  • [output] integer

Tests:
Solution(C#):

int constructSquare(string s) {
    List<int> letterCnt = new List<int>();
    for (int i = 0; i < 26; i++) {
        letterCnt.Add(0);
    }
    for (int i = 0; i < s.Length; i++) {
        letterCnt[s[i]-'a']++;
    }
  
    letterCnt.Sort();
    int best = -1;

    int minNumber = (int)Math.Pow(10, s.Length - 1);
    for (int k = (int)Math.Floor(Math.Sqrt(minNumber)); k * k < minNumber * 10; k++) {
        int n = k * k;
        List<int> digitCnt = new List<int>();
        for (int i = 0; i < 26; i++) {
            digitCnt.Add(0);
        }
        while (n > 0) {
            digitCnt[n % 10]++;
            n = n / 10;
        }
    
        digitCnt.Sort();
        if (Enumerable.SequenceEqual(letterCnt, digitCnt)) {
            best = k * k;
        }
    }
    return best;
}


Advertisements