Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
[ad_1]
Given a string S of size N consisting of digits and an integer Okay, Scale back the string by performing the next operation until the size of the string is larger than Okay:
Examples:
Enter: S = “11111222223”, Okay = 3
Output: “135”
Clarification:
For the primary spherical, divide S into teams of measurement 3: “111”, “112”, “222”, and “23”.
Then calculate the digit sum of every group:
1 + 1 + 1 = 3, 1 + 1 + 2 = 4, 2 + 2 + 2 = 6, and a couple of + 3 = 5.
So, string turns into “3” + “4” + “6” + “5” = “3465”.
For the second spherical, divide s into “346” and “5”.
Then calculate the digit sum of every group: 3 + 4 + 6 = 13, 5 = 5.
So, string turns into “13” + “5” = “135”.
After second spherical. Now, size of S <= Okay, so return “135” as the reply.Enter: S = “1123”, Okay = 2
Output: “25”
Clarification: For the primary spherical, divide S into teams of measurement 2: “11”, “23”.
Then we calculate the digit sum of every group: 1 + 1 = 2 and a couple of + 3 = 5.
So, String turns into “2” + “5” = “25” after the primary spherical.
Now, size of S <= Okay, so return “25” as the reply.
Strategy: This can be a easy implementation primarily based downside. The answer is as follows:
Iterate S till its measurement is larger than Okay. In each iteration, divide the string in consecutive Okay sized teams, get their sum and add them to type the brand new string.
Observe the under steps to implement the concept:
Beneath is the implementation for the above strategy:
|
Time Complexity: O(N * Okay)
Auxiliary House: O(1)
[ad_2]