You are given a string s of length n and an integer k, where n is a multiple of k. Your task is to hash the string s into a new string called result, which has a length of n / k.
First, divide s into n / k substrings, each with a length of k. Then, initialize result as an empty string.
For each substring in order from the beginning:
'a' → 0, 'b' → 1, ..., 'z' → 25).hashedChar.hashedChar.result.Return result.
Example 1:
Input: s = "abcd", k = 2
Output: "bf"
Explanation:
First substring: "ab", 0 + 1 = 1, 1 % 26 = 1, result[0] = 'b'.
Second substring: "cd", 2 + 3 = 5, 5 % 26 = 5, result[1] = 'f'.
Example 2:
Input: s = "mxz", k = 3
Output: "i"
Explanation:
The only substring: "mxz", 12 + 23 + 25 = 60, 60 % 26 = 8, result[0] = 'i'.
Constraints:
1 <= k <= 100k <= s.length <= 1000s.length is divisible by k.s consists only of lowercase English letters.We will divide the string s into multiple substrings each of length k. For each substring, we calculate the sum of hash values of its characters and use the modulus operator to find the appropriate character in the alphabet to append to the result string.
The solution works by dividing s into equal parts of k and calculating the sum of alphabetical indices of each substring, then taking the modulus by 26 to find the corresponding character to add to the result string.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), with n being the length of s. Space Complexity: O(n/k).
8 patterns to solve 80% Leetcode problems • Sahil & Sarra • 656,704 views views
Watch 9 more video solutions →Practice Hash Divided String with our built-in code editor and test cases.
Practice on FleetCode