Leetcode-2156

Find Substring With Given Hash Value

2156. Find Substring With Given Hash Value

The hash of a 0-indexed string s of length k, given integers p and m, is computed using the following function:

Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26.

You are given a string s and the integers power, modulo, k, and hashValue. Return sub, the first substring of s of length k such that hash(sub, power, modulo) == hashValue.

The test cases will be generated such that an answer always exists.

A substring is a contiguous non-empty sequence of characters within a string.

Example 1:

Input: s = "leetcode", power = 7, modulo = 20, k = 2, hashValue = 0 Output: "ee" Explanation: The hash of “ee” can be computed to be hash(“ee”, 7, 20) = (5 * 1 + 5 * 7) \pmod{20} = 40 \pmod{20} = 0. “ee” is the first substring of length 2 with hashValue 0. Hence, we return “ee”.

Example 2:

Input: s = "fbxzaad", power = 31, modulo = 100, k = 3, hashValue = 32 Output: "fbx" Explanation: The hash of “fbx” can be computed to be hash(“fbx”, 31, 100) = (6 * 1 + 2 * 31 + 24 * 31^2) \pmod{100} = 23132 \pmod{100} = 32. The hash of “bxz” can be computed to be hash(“bxz”, 31, 100) = (2 * 1 + 24 * 31 + 26 * 31^2) \pmod{100} = 25732 \pmod{100} = 32. “fbx” is the first substring of length 3 with hashValue 32. Hence, we return “fbx”. Note that “bxz” also has a hash of 32 but it appears later than “fbx”.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <cstring>

class Solution {
public:
    std::string subStrHash(std::string s, int power, int modulo, int k, int hashValue) {
        long long sum = 0, opt = 1;
        int n = s.length() - k;
        int res = n;
        for (int i = k - 1; i >= 0; --i) {
            sum = (sum * power + val(s[i + n])) % modulo;
            opt = (opt * power) % modulo;
        }
        
        for (int i = n - 1; i >= 0; --i) {
            sum = (sum * power + val(s[i])) % modulo;
            sum = (sum + modulo - val(s[i + k]) * opt % modulo) % modulo;
            if (sum == hashValue) {
                res = i;
            }
        }
        
        return s.substr(res, k);
    }
    
private:
    inline int val(char c) {
        return c - 'a' + 1;
    }
};

Leetcode-2156