We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Hash Divided String

Number: 3540

Difficulty: Medium

Paid? No

Companies: N/A


Problem Description

Given a string s whose length n is a multiple of an integer k, divide s into n/k substrings of length k. For each substring, compute the sum of the positions of its characters in the alphabet (where a maps to 0, b maps to 1, …, z maps to 25), take the sum modulo 26, and map the result back to a lowercase letter. Append each mapped letter to form the final result string.


Key Insights

  • The string can be evenly divided into substrings because n is a multiple of k.
  • For each substring, calculate a hash by summing the positional values of its characters.
  • Use modulo operation (mod 26) to convert the sum to a valid alphabet index.
  • Map the resulting index to the corresponding lowercase letter.
  • Concatenate these letters to form the result.

Space and Time Complexity

Time Complexity: O(n) where n is the length of the string, as we iterate over each character once. Space Complexity: O(n/k) for storing the resulting string, which in the worst case is O(n).


Solution

We first split the string into chunks of length k. For each chunk, we iterate through its characters, converting each character to its alphabetical index by subtracting the ASCII value of 'a'. We sum these indices, take the modulo 26 of the sum, and convert the result back to a character by adding the ASCII value of 'a'. Finally, we build the output string by appending each resulting character.

The primary data structures used are:

  • A loop to iterate over the characters of s.
  • A variable to accumulate the sum of indices for each substring.
  • A string to keep the final result.

The approach is straightforward simulation and string manipulation, ensuring that all characters are processed efficiently.


Code Solutions

# Python solution with detailed comments

def hash_divided_string(s: str, k: int) -> str:
    # Initialize the result string as empty
    result = ""
    # Process the string in chunks of length k
    for i in range(0, len(s), k):
        # Get the current substring of length k
        substring = s[i:i+k]
        # Compute the sum of the positions of each character
        char_sum = 0
        for char in substring:
            # Convert character to its corresponding value (a->0, b->1, ..., z->25)
            char_sum += ord(char) - ord('a')
        # Take modulo 26 to get the hash value
        hash_value = char_sum % 26
        # Convert the hash value back to a character
        result += chr(hash_value + ord('a'))
    return result

# Example usage:
print(hash_divided_string("abcd", 2))  # Output: "bf"
print(hash_divided_string("mxz", 3))   # Output: "i"
← Back to All Questions