| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.TotalCharactersInStringAfterTransformations1; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class TotalCharactersInStringAfterTransformations1Counting : ITotalCharactersInStringAfterTransformations1 |
| | 16 | | { |
| | 17 | | private const int Modulo = 1_000_000_007; |
| | 18 | | private const byte AlphabetLength = 'z' - 'a' + 1; |
| | 19 | |
|
| | 20 | | /// <summary> |
| | 21 | | /// Time complexity - O(n) |
| | 22 | | /// Space complexity - O(1) |
| | 23 | | /// </summary> |
| | 24 | | /// <param name="input"></param> |
| | 25 | | /// <param name="transformationsCount"></param> |
| | 26 | | /// <returns></returns> |
| | 27 | | public int LengthAfterTransformations(string input, int transformationsCount) |
| 3 | 28 | | { |
| 3 | 29 | | Span<long> frequencies = stackalloc long[AlphabetLength]; |
| | 30 | |
|
| 29 | 31 | | foreach (var c in input) |
| 10 | 32 | | { |
| 10 | 33 | | frequencies[c - 'a']++; |
| 10 | 34 | | } |
| | 35 | |
|
| 9 | 36 | | while (transformationsCount > 0) |
| 6 | 37 | | { |
| 218 | 38 | | for (var i = AlphabetLength - 1; i >= 0 && transformationsCount > 0; i--) |
| 103 | 39 | | { |
| 103 | 40 | | if (frequencies[i] > 0) |
| 12 | 41 | | { |
| 12 | 42 | | var nextIndex = i + 1; |
| | 43 | |
|
| 12 | 44 | | if (nextIndex >= AlphabetLength) |
| 5 | 45 | | { |
| 5 | 46 | | nextIndex = 0; |
| 5 | 47 | | } |
| | 48 | |
|
| 12 | 49 | | frequencies[nextIndex] = (frequencies[nextIndex] + frequencies[i]) % Modulo; |
| 12 | 50 | | } |
| | 51 | |
|
| 103 | 52 | | transformationsCount--; |
| 103 | 53 | | } |
| 6 | 54 | | } |
| | 55 | |
|
| 3 | 56 | | long result = 0; |
| | 57 | |
|
| 165 | 58 | | foreach (var frequency in frequencies) |
| 78 | 59 | | { |
| 78 | 60 | | result = (result + frequency) % Modulo; |
| 78 | 61 | | } |
| | 62 | |
|
| 3 | 63 | | return (int)result; |
| 3 | 64 | | } |
| | 65 | | } |