|
| 1 | +/** |
| 2 | + * 2156. Find Substring With Given Hash Value |
| 3 | + * https://leetcode.com/problems/find-substring-with-given-hash-value/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * The hash of a 0-indexed string s of length k, given integers p and m, is computed using |
| 7 | + * the following function: |
| 8 | + * - hash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m. |
| 9 | + * |
| 10 | + * Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26. |
| 11 | + * |
| 12 | + * You are given a string s and the integers power, modulo, k, and hashValue. Return sub, the |
| 13 | + * first substring of s of length k such that hash(sub, power, modulo) == hashValue. |
| 14 | + * |
| 15 | + * The test cases will be generated such that an answer always exists. |
| 16 | + * |
| 17 | + * A substring is a contiguous non-empty sequence of characters within a string. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | +* @param {string} s |
| 22 | +* @param {number} power |
| 23 | +* @param {number} modulo |
| 24 | +* @param {number} k |
| 25 | +* @param {number} hashValue |
| 26 | +* @return {string} |
| 27 | +*/ |
| 28 | +var subStrHash = function(s, power, modulo, k, hashValue) { |
| 29 | + power = BigInt(power); |
| 30 | + modulo = BigInt(modulo); |
| 31 | + hashValue = BigInt(hashValue); |
| 32 | + |
| 33 | + const powers = new Array(k); |
| 34 | + powers[0] = 1n; |
| 35 | + for (let i = 1; i < k; i++) { |
| 36 | + powers[i] = (powers[i - 1] * power) % modulo; |
| 37 | + } |
| 38 | + |
| 39 | + for (let start = 0; start <= s.length - k; start++) { |
| 40 | + let hash = 0n; |
| 41 | + for (let i = 0; i < k; i++) { |
| 42 | + const charVal = BigInt(s.charCodeAt(start + i) - 'a'.charCodeAt(0) + 1); |
| 43 | + hash = (hash + charVal * powers[i]) % modulo; |
| 44 | + } |
| 45 | + if (hash === hashValue) { |
| 46 | + return s.substring(start, start + k); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + return ''; |
| 51 | +}; |
0 commit comments