Hash Divided String - Problem

Imagine you're a cryptographer creating a simple hash function for string data! You're given a string s of length n and an integer k, where n is perfectly divisible by k.

Your mission is to transform the original string into a compressed hash string of length n/k using the following algorithm:

  1. Divide: Split the string s into n/k substrings, each exactly k characters long
  2. Hash: For each substring, calculate a hash value by:
    • Converting each character to its alphabet position ('a' → 0, 'b' → 1, ..., 'z' → 25)
    • Summing all these position values
    • Taking the remainder when divided by 26 (this keeps us within alphabet bounds)
  3. Encode: Convert the hash value back to its corresponding lowercase letter
  4. Append: Add this character to your result string

Goal: Return the final hashed string that represents a compressed version of the original input.

Example: If s = "abcd" and k = 2, we get substrings "ab" and "cd". Hash of "ab" = (0+1) % 26 = 1 → 'b', Hash of "cd" = (2+3) % 26 = 5 → 'f'. Result: "bf"

Input & Output

example_1.py — Basic Case
$ Input: s = "abcd", k = 2
Output: "bf"
💡 Note: Divide "abcd" into ["ab", "cd"]. For "ab": (0+1) % 26 = 1 → 'b'. For "cd": (2+3) % 26 = 5 → 'f'. Result: "bf"
example_2.py — Larger Substring
$ Input: s = "mxz", k = 3
Output: "i"
💡 Note: Only one substring "mxz". Hash: (12+23+25) % 26 = 60 % 26 = 8 → 'i'. Result: "i"
example_3.py — Multiple Substrings
$ Input: s = "abcdef", k = 3
Output: "dm"
💡 Note: Divide into ["abc", "def"]. For "abc": (0+1+2) % 26 = 3 → 'd'. For "def": (3+4+5) % 26 = 12 → 'm'. Result: "dm"

Constraints

  • 1 ≤ k ≤ n ≤ 100
  • n is a multiple of k
  • s consists of lowercase English letters only
  • The result string will have length n/k

Visualization

Tap to expand
String Hashing Assembly LineInput: "abcd", k=2abcdDivide into chunksabcdConvert to positions0+1, 2+3Calculate sums1, 5Apply modulo 261%26=1, 5%26=5Convert to charactersb, fResult: "bf"bfHash FunctionΣ(char_pos)mod 26
Understanding the Visualization
1
Input Division
Raw string gets cut into equal-sized chunks of length k
2
Character Encoding
Each character in a chunk gets converted to its alphabet position (a=0, b=1, etc.)
3
Sum Calculation
All position values in the chunk are added together
4
Hash Modulation
The sum is reduced using modulo 26 to stay within alphabet bounds
5
Character Output
The final hash value is converted back to a lowercase letter
Key Takeaway
🎯 Key Insight: Each substring can be processed independently, making this an embarrassingly parallel problem that naturally divides the work into equal chunks.
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
28.5K Views
Medium Frequency
~8 min Avg. Time
892 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