Hash Divided String - Problem

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.

Process:

1. First, divide s into n / k substrings, each with a length of k.

2. Initialize result as an empty string.

3. For each substring in order from the beginning:

  • The hash value of a character is the index of that character in the English alphabet (e.g., 'a' → 0, 'b' → 1, ..., 'z' → 25).
  • Calculate the sum of all the hash values of the characters in the substring.
  • Find the remainder of this sum when divided by 26, which is called hashedChar.
  • Identify the character in the English lowercase alphabet that corresponds to hashedChar.
  • Append that character to the end of result.

Return result.

Input & Output

Example 1 — Basic Case
$ Input: s = "abcd", k = 2
Output: "bf"
💡 Note: Substring "ab": hash sum = 0 + 1 = 1, 1 % 26 = 1 → 'b'. Substring "cd": hash sum = 2 + 3 = 5, 5 % 26 = 5 → 'f'. Result: "bf"
Example 2 — Single Character Groups
$ Input: s = "xyz", k = 1
Output: "xyz"
💡 Note: Each character forms its own substring: 'x' → 23 % 26 = 23 → 'x', 'y' → 24 % 26 = 24 → 'y', 'z' → 25 % 26 = 25 → 'z'
Example 3 — Wraparound Case
$ Input: s = "zzab", k = 2
Output: "yb"
💡 Note: Substring "zz": hash sum = 25 + 25 = 50, 50 % 26 = 24 → 'y'. Substring "ab": hash sum = 0 + 1 = 1, 1 % 26 = 1 → 'b'. Result: "yb"

Constraints

  • 1 ≤ s.length ≤ 1000
  • 1 ≤ k ≤ s.length
  • s.length is a multiple of k
  • s consists of lowercase English letters only

Visualization

Tap to expand
Hash Divided String - Single Pass Processing INPUT String s = "abcd" a b c d 0 1 2 3 Substring 1 Substring 2 Parameters k = 2 (substring length) n/k = 4/2 = 2 substrings Hash: a=0, b=1, c=2... ...x=23, y=24, z=25 ALGORITHM STEPS 1 Divide String Split into k-length parts "abcd" --> ["ab", "cd"] 2 Sum Hash Values Add character indices "ab": 0+1 = 1 "cd": 2+3 = 5 3 Modulo 26 Get remainder (hashedChar) 1 % 26 = 1 --> 'b' 5 % 26 = 5 --> 'f' 4 Append to Result Build final string FINAL RESULT Hashed String: b f index 1 index 5 Output: "bf" Summary "ab" --> sum=1 --> 'b' "cd" --> sum=5 --> 'f' result = "b" + "f" = "bf" OK Key Insight: Single pass processing: Each substring is processed independently. Sum all character indices, take mod 26 to get a valid alphabet index (0-25), then convert back to character ('a' + index). Time: O(n), Space: O(n/k) for result string. The modulo ensures the result is always a lowercase letter. TutorialsPoint - Hash Divided String | Single Pass Processing Approach
Asked in
Google 15 Microsoft 12 Amazon 8
12.0K Views
Medium Frequency
~15 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen