Rolling Hash Variable
Programming Interview
Hard
5 views
Problem Description
You're given {x}. Compute rolling hash: h=0; for each char c: h=(h*B+ord(c))%M. Output h.
Input Format
Line1: s. Line2: B M.
Output Format
One integer hash.
Sample Test Case
Input:
abc
911382 1000000007
Official Solution
import sys
txt=sys.stdin.read().splitlines()
if not txt: sys.exit(0)
s=txt[0].rstrip('\
')
if len(txt)<2: sys.exit(0)
B,M=map(int,txt[1].split())
h=0
for ch in s:
h=(h*B+ord(ch))%M
sys.stdout.write(str(h))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!