question_slug stringlengths 3 77 | title stringlengths 1 183 | slug stringlengths 12 45 | summary stringlengths 1 160 ⌀ | author stringlengths 2 30 | certification stringclasses 2
values | created_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | updated_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | hit_count int64 0 10.6M | has_video bool 2
classes | content stringlengths 4 576k | upvotes int64 0 11.5k | downvotes int64 0 358 | tags stringlengths 2 193 | comments int64 0 2.56k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
longest-increasing-subsequence-ii | [Java] Original LIS solution (No segment tree) | java-original-lis-solution-no-segment-tr-7x4o | Use the same idea as the original LIS, just instead of storing the smallest possible number, here we need to store the whole sequence.\n\n\n public int lengt | wddd | NORMAL | 2022-09-11T05:36:58.049556+00:00 | 2022-09-14T02:27:38.611803+00:00 | 644 | false | Use the same idea as the original LIS, just instead of storing the smallest possible number, here we need to store the whole sequence.\n\n```\n public int lengthOfLIS(int[] nums, int k) {\n List<List<Integer>> tails = new ArrayList<>();\n\n for (int num : nums) {\n int ind = Collections.binarySearch(tails, List.of(num), Comparator.comparingInt(i -> i.get(0)));\n if (ind < 0) {\n ind = ~ind;\n while (ind > 0) {\n List<Integer> prevNums = tails.get(ind - 1);\n int insertInd = Collections.binarySearch(prevNums, num);\n if (insertInd < 0) {\n insertInd = ~insertInd;\n }\n\n if (insertInd > 0 && prevNums.get(insertInd - 1) >= num - k) {\n break;\n } else {\n ind--;\n }\n }\n insertToList(tails, ind, num);\n }\n }\n\n return tails.size();\n }\n\n private void insertToList(List<List<Integer>> tails, int ind, int num) {\n if (ind == tails.size()) {\n tails.add(new ArrayList<>());\n }\n\n int insertInd = Collections.binarySearch(tails.get(ind), num);\n if (insertInd < 0) {\n insertInd = ~insertInd;\n tails.get(ind).add(insertInd, num);\n }\n }\n``` | 1 | 0 | ['Binary Tree'] | 0 |
longest-increasing-subsequence-ii | javascript Segment Tree Range Min Query 281ms | javascript-segment-tree-range-min-query-jc3yf | \n///////////////////////////////////////////// Template ///////////////////////////////////////////////////////////\n// using array format\nfunction SegmentTre | henrychen222 | NORMAL | 2022-09-11T05:28:09.621797+00:00 | 2022-09-11T05:36:54.705988+00:00 | 233 | false | ```\n///////////////////////////////////////////// Template ///////////////////////////////////////////////////////////\n// using array format\nfunction SegmentTreeRMQ(n) {\n let h = Math.ceil(Math.log2(n)), len = 2 * 2 ** h, a = Array(len).fill(Number.MAX_SAFE_INTEGER);\n h = 2 ** h;\n return { update, minx, indexOf, tree }\n function update(pos, v) {\n a[h + pos] = v;\n for (let i = parent(h + pos); i >= 1; i = parent(i)) propagate(i);\n }\n function propagate(i) {\n a[i] = Math.min(a[left(i)], a[right(i)]);\n }\n function minx(l, r) {\n let min = Number.MAX_SAFE_INTEGER;\n if (l >= r) return min;\n l += h;\n r += h;\n for (; l < r; l = parent(l), r = parent(r)) {\n if (l & 1) min = Math.min(min, a[l++]);\n if (r & 1) min = Math.min(min, a[--r]);\n }\n return min;\n }\n function indexOf(l, v) {\n if (l >= h) return -1;\n let cur = h + l;\n while (1) {\n if (a[cur] <= v) {\n if (cur >= h) return cur - h;\n cur = left(cur);\n } else {\n cur++;\n if ((cur & cur - 1) == 0) return -1;\n if (cur % 2 == 0) cur = parent(cur);\n }\n }\n }\n function parent(i) {\n return i >> 1;\n }\n function left(i) {\n return 2 * i;\n }\n function right(i) {\n return 2 * i + 1;\n }\n function tree() {\n return a;\n }\n}\n//////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\nconst lengthOfLIS = (a, k) => {\n let max = Math.max(...a), st = new SegmentTreeRMQ(max + 3), res = 0;\n for (const x of a) {\n let l = Math.max(x-k, 0), r = x;\n let min = st.minx(l, r), maxL = min == Number.MAX_SAFE_INTEGER ? 0 : -min;\n maxL++;\n res = Math.max(res, maxL);\n st.update(x, -maxL);\n }\n return res;\n};\n```\nsimilar problem using same template\nhttps://leetcode.com/problems/booking-concert-tickets-in-groups/\nhttps://leetcode.com/problems/maximum-distance-between-a-pair-of-values/\nhttps://leetcode.com/problems/jump-game-vi/\n\nmy solution:\nhttps://leetcode.com/problems/booking-concert-tickets-in-groups/discuss/2085140/javascript-segment-tree-(range-min-query)-%2B-fenwick-(query-prefix-sum)-560ms\nhttps://leetcode.com/problems/maximum-distance-between-a-pair-of-values/discuss/1198943/javascript-segment-tree-range-min-query-296ms\nhttps://leetcode.com/problems/jump-game-vi/discuss/981037/javascript-SegmentTreeRMQ-312ms | 1 | 0 | ['Tree', 'JavaScript'] | 1 |
longest-increasing-subsequence-ii | Rust | Segment Tree | With Comments | rust-segment-tree-with-comments-by-walli-vvdf | This is my unrevised submission for the 2022-09-11 Weekly Contest 310. This is a DP problem - add one to the path length of the longest path found so far among | wallicent | NORMAL | 2022-09-11T04:28:32.123891+00:00 | 2022-09-11T10:51:06.424577+00:00 | 138 | false | This is my unrevised submission for the 2022-09-11 Weekly Contest 310. This is a DP problem - add one to the path length of the longest path found so far among the numbers that are no less than k smaller than the current number. But the difficult part is that the O(n^2) needed for a standard implementation is too slow. So we need a segment max tree to be able to do O(log(n)) searches for the max DP entry within an interval. \n\nComment: So very happy that I managed to solve the hard problem for this contest. I first did the simple bottom-up DP solution, and didn\'t understand what was so hard about the problem until I submitted. I had recently done a segment sum tree, so with that in mind, I quickly made a similar segment max tree. Even then, some minor bugs tripped me up for a long time, and I got the working solution submitted with two minutes left to go. Phew.\n\n```\npub struct SegmentTree<T> {\n n: usize,\n tree: Vec<T>,\n}\n\nimpl<T> SegmentTree<T>\nwhere\n T: Copy + Ord + Default,\n{\n pub fn new(nums: &[T]) -> Self {\n let n = nums.len();\n let mut tree: Vec<_> = std::iter::repeat(T::default())\n .take(n)\n .chain(nums.iter().copied())\n .collect();\n for i in (1..n).rev() {\n tree[i] = tree[2 * i].max(tree[2 * i + 1]);\n }\n Self { n, tree }\n }\n\n pub fn update(&mut self, index: usize, val: T) {\n let mut i = index + self.n;\n self.tree[i] = val;\n while i > 0 {\n let (child1, child2) = (i, if i % 2 == 0 { i + 1 } else { i - 1 });\n i /= 2;\n self.tree[i] = self.tree[child1].max(self.tree[child2]);\n }\n }\n\n pub fn max_range(&self, left: usize, right: usize) -> T {\n let (mut left, mut right) = (left as usize + self.n, right as usize + self.n);\n let mut max = T::default();\n while left <= right {\n if left % 2 == 1 {\n max = max.max(self.tree[left]);\n left += 1;\n }\n if right % 2 == 0 {\n max = max.max(self.tree[right]);\n right -= 1;\n }\n left /= 2;\n right /= 2;\n }\n max\n }\n}\n\nimpl Solution {\n pub fn length_of_lis(nums: Vec<i32>, k: i32) -> i32 {\n let n = nums.len();\n let mut dp = SegmentTree::new(&[0; 100002]);\n let mut global_max = 1;\n for i in 0..n {\n let (low, high) = (0.max(nums[i]-k) as usize, 0.max(nums[i] - 1) as usize);\n let max = dp.max_range(low, high) + 1;\n global_max = global_max.max(max);\n dp.update(nums[i] as usize, max);\n }\n global_max\n }\n}\n``` | 1 | 0 | ['Rust'] | 1 |
longest-increasing-subsequence-ii | [Python3] segment tree | python3-segment-tree-by-ye15-9cio | Please pull this commit for solutions of weekly 310. \n\n\nclass SegTree: \n\n def __init__(self, arr: List[int]): \n self.n = len(arr)\n self. | ye15 | NORMAL | 2022-09-11T04:20:04.126765+00:00 | 2022-09-14T19:47:49.639582+00:00 | 1,106 | false | Please pull this [commit](https://github.com/gaosanyong/leetcode/commit/b89b2c654a0b8ced9885ecdb433ad5f929a1d4b4) for solutions of weekly 310. \n\n```\nclass SegTree: \n\n def __init__(self, arr: List[int]): \n self.n = len(arr)\n self.tree = [0] * (2*self.n)\n # for i in range(2*self.n-1, 0, -1): \n # if i >= self.n: self.tree[i] = arr[i - self.n]\n # else: self.tree[i] = max(self.tree[i<<1], self.tree[i<<1|1])\n\n def query(self, lo: int, hi: int) -> int: \n ans = 0 \n lo += self.n \n hi += self.n\n while lo < hi: \n if lo & 1: \n ans = max(ans, self.tree[lo])\n lo += 1\n if hi & 1: \n hi -= 1\n ans = max(ans, self.tree[hi])\n lo >>= 1\n hi >>= 1\n return ans \n\n def update(self, i: int, val: int) -> None: \n i += self.n \n self.tree[i] = val\n while i > 1: \n self.tree[i>>1] = max(self.tree[i], self.tree[i^1])\n i >>= 1\n\nclass Solution:\n def lengthOfLIS(self, nums: List[int], k: int) -> int:\n m = max(nums)\n ans = 0 \n tree = SegTree([0] * (m+1))\n for x in nums: \n val = tree.query(max(0, x-k), x) + 1\n ans = max(ans, val)\n tree.update(x, val)\n return ans \n``` | 1 | 0 | ['Python3'] | 2 |
longest-increasing-subsequence-ii | Segment Tree || C++ | segment-tree-c-by-kishan_akbari-5plj | Firstly,you have to create array of size 1e5+100, because values of array is 1<=v[i]<=1e5. Assume that Array name is \'Seg\'\nNow, you have to insert elements o | Kishan_Akbari | NORMAL | 2022-09-11T04:08:13.619590+00:00 | 2022-09-11T04:08:13.619617+00:00 | 232 | false | Firstly,you have to create array of size 1e5+100, because values of array is 1<=v[i]<=1e5. Assume that Array name is \'Seg\'\nNow, you have to insert elements one by one. Assume that you Reached element at index i and value of that element is X. now you have to find maximam value of rang Seg[X-k,X-1]. To find this maximam value of rang you have to use \'segment-tree\'.\nAssume that vales of rang is mx1. Now you have to udate that value with previous one. To do this you have to use \'lazy-propagation\'.\n\n\n```\nclass Solution {\npublic:\n int lengthOfLIS(vector<int>& v1, int k) {\n // v = {1,-10,5,6,10};\n // int n = v.size();\n \n int ra = (1e5+100);\n vector<int> v(ra);\n vector<int> segtree(4*ra),lazy(4*ra);\n function<int(int,int,int)> makeseg = [&](int s,int e,int po)\n {\n \n if(s==e)\n return segtree[po] = v[s];\n return segtree[po] = max(makeseg(s,(s+e)/2,2*po+1),makeseg((s+e)/2+1,e,2*po+2));\n };\n \n makeseg(0,ra-1,0);\n \n function<void(int,int,int,int,int,int)> changelazy = [&](int s,int e,int ps,int pe,int val,int po)\n {\n if(e<s)\n return ;\n \n if(lazy[po]!=0)\n {\n segtree[po] += lazy[po];\n if(s!=e)\n {\n lazy[2*po + 1] += lazy[po];\n lazy[2*po + 2] += lazy[po];\n }\n \n lazy[po] = 0;\n }\n \n \n if(e<ps || s>pe){\n return ;\n }\n \n if(ps<=s && e<=pe) \n {\n segtree[po] += val;\n if(s!=e)\n {\n lazy[2*po+1] += val;\n lazy[2*po+2] += val;\n }\n \n return ;\n }\n \n int mid = (s+e)/2;\n \n changelazy(s,mid,ps,pe,val,2*po+1);\n changelazy(mid+1,e,ps,pe,val,2*po+2);\n segtree[po] = max(segtree[2*po+1],segtree[2*po+2]);\n \n };\n \n \n function<int(int,int,int,int,int)> getmin = [&](int s,int e,int ps,int pe,int po)\n { \n if(lazy[po]!=0)\n {\n segtree[po] += lazy[po];\n if(s!=e)\n {\n lazy[2*po + 1] += lazy[po];\n lazy[2*po + 2] += lazy[po];\n }\n \n lazy[po] = 0;\n }\n \n \n if(ps<=s && e<=pe){\n return segtree[po];\n }\n if(e<ps || s>pe)\n return (int)(0);\n \n int mid = (s+e)/2;\n \n return max(getmin(s,mid,ps,pe,2*po+1),getmin(mid+1,e,ps,pe,2*po+2));\n };\n \n int ans = 0;\n for(int i=0; i<(int)v1.size(); ++i)\n {\n int x = v1[i];\n int mx = getmin(0,ra-1,max(x-k,0),x-1,0);\n ans = max(ans,mx+1);\n int ele = getmin(0,ra-1,x,x,0);\n ele = mx+1-ele;\n changelazy(0,ra-1,x,x,ele,0);\n }\n \n \n return ans;\n \n \n \n \n }\n};\n``` | 1 | 0 | ['Dynamic Programming'] | 0 |
longest-increasing-subsequence-ii | [C++] An easy solution using segment tree | c-an-easy-solution-using-segment-tree-by-zd43 | \n// find smallest x s.t. n <= 2^x\nint ceil_pow2(int n) {\n int x = 0;\n while ((1U << x) < (unsigned int)(n)) x++;\n return x;\n}\n\n// segment tree\ | martin0327 | NORMAL | 2022-09-11T04:03:05.776010+00:00 | 2022-09-11T05:19:47.704180+00:00 | 285 | false | ```\n// find smallest x s.t. n <= 2^x\nint ceil_pow2(int n) {\n int x = 0;\n while ((1U << x) < (unsigned int)(n)) x++;\n return x;\n}\n\n// segment tree\ntemplate <class S, S (*op)(S, S), S (*e)()> struct segtree {\n public:\n segtree() : segtree(0) {}\n segtree(int n) : segtree(std::vector<S>(n, e())) {}\n segtree(const std::vector<S>& v) : _n(int(v.size())) {\n log = ceil_pow2(_n);\n size = 1 << log;\n d = std::vector<S>(2 * size, e());\n for (int i = 0; i < _n; i++) d[size + i] = v[i];\n for (int i = size - 1; i >= 1; i--) {\n update(i);\n }\n }\n\n void set(int p, S x) {\n assert(0 <= p && p < _n);\n p += size;\n d[p] = x;\n for (int i = 1; i <= log; i++) update(p >> i);\n }\n\n S get(int p) {\n assert(0 <= p && p < _n);\n return d[p + size];\n }\n\n S prod(int l, int r) {\n assert(0 <= l && l <= r && r <= _n);\n S sml = e(), smr = e();\n l += size;\n r += size;\n\n while (l < r) {\n if (l & 1) sml = op(sml, d[l++]);\n if (r & 1) smr = op(d[--r], smr);\n l >>= 1;\n r >>= 1;\n }\n return op(sml, smr);\n }\n\n S all_prod() { return d[1]; }\n\n template <bool (*f)(S)> int max_right(int l) {\n return max_right(l, [](S x) { return f(x); });\n }\n template <class F> int max_right(int l, F f) {\n assert(0 <= l && l <= _n);\n assert(f(e()));\n if (l == _n) return _n;\n l += size;\n S sm = e();\n do {\n while (l % 2 == 0) l >>= 1;\n if (!f(op(sm, d[l]))) {\n while (l < size) {\n l = (2 * l);\n if (f(op(sm, d[l]))) {\n sm = op(sm, d[l]);\n l++;\n }\n }\n return l - size;\n }\n sm = op(sm, d[l]);\n l++;\n } while ((l & -l) != l);\n return _n;\n }\n\n template <bool (*f)(S)> int min_left(int r) {\n return min_left(r, [](S x) { return f(x); });\n }\n template <class F> int min_left(int r, F f) {\n assert(0 <= r && r <= _n);\n assert(f(e()));\n if (r == 0) return 0;\n r += size;\n S sm = e();\n do {\n r--;\n while (r > 1 && (r % 2)) r >>= 1;\n if (!f(op(d[r], sm))) {\n while (r < size) {\n r = (2 * r + 1);\n if (f(op(d[r], sm))) {\n sm = op(d[r], sm);\n r--;\n }\n }\n return r + 1 - size;\n }\n sm = op(d[r], sm);\n } while ((r & -r) != r);\n return 0;\n }\n\n private:\n int _n, size, log;\n std::vector<S> d;\n\n void update(int k) { d[k] = op(d[2 * k], d[2 * k + 1]); }\n};\n\n// merge operation and identity function for segtree\nint op(int a, int b) {return max(a, b);}\nint e() {return 0;} \n\nclass Solution {\npublic:\n int lengthOfLIS(vector<int>& a, int k) {\n int n = a.size();\n\n // max segment tree: The x-th element of it stores the max length of desired subsequence that ends with x so far.\n segtree<int, op, e> dp(1e5+1); // is initially set with all zero\'s\n\n for (auto x : a) {\n // x is the current number being considered\n \n // find the maximum among the max lengths of desired subsequence so far that ends with numbers y s.t. x-k <= y < x\n int max_len = dp.prod(max(0,x-k),x); \n \n // the max length of the desired subsequence that ends with x is max_len+1\n dp.set(x,max_len+1); \n }\n // return the maximum length of all desired subsequences\n return dp.all_prod();\n }\n};\n``` | 1 | 1 | ['Dynamic Programming', 'Tree'] | 0 |
longest-increasing-subsequence-ii | c++ dp || o(nlog(n)) || SEGMENT TREE | c-dp-onlogn-segment-tree-by-aniketash57-n00d | \n\t/*\n\t\tsubproblem first you guys can try finding longest increasing subsequence in nlog(n) using a map \n\t\tafter that instead of map if you use segment t | aniketash57 | NORMAL | 2022-09-11T04:01:07.004273+00:00 | 2022-09-11T04:37:29.813056+00:00 | 1,100 | false | ```\n\t/*\n\t\tsubproblem first you guys can try finding longest increasing subsequence in nlog(n) using a map \n\t\tafter that instead of map if you use segment tree you can find max of k elements smaller than current element in logirithmic time \n\t*/\n\tstruct node{\n\t\tint x;\n\t\tnode()\n\t\t{\n\t\t\tx=-inf;\n\t\t}\n\t};\n\tstruct segtree{\n\t\n\t\tvector<int> arr;\n\t\tnode merge( node a, node b) \n\t\t{ \n\t\t\tnode z ;\n\t\t\tz.x=max(a.x,b.x);\n\t\t\treturn z;\n\t\t}\n\t\tvector<node> t;\n\t\tsegtree( int n)\n\t\t{ \n\t\t\t\n\t\t\tarr.assign(n,0);\n\t\t\tt.resize(4*n);\n\t\t\t\n\t\t}\n\t\tsegtree(vi& a) \n\t\t{ \n\t\t\tarr = a;\n\t\t\tt.resize(4*sz(arr));\n\t\t\t\n\t\t}\n\tvoid build(int ind , int l ,int r) \n\t{ \n\t\t//making a node which is responsible for l to r \n\t\tif(l==r) \n\t\t{ \n\t\t\tt[ind].x=arr[l];\n\t\t\treturn ;\n\t\t}\n\t\tint mid = l+((r-l)>>1);\n\t\tbuild((ind<<1),l,mid) ;//building left tree \n\t\tbuild(((ind<<1) |1),mid+1,r);//building right tree\n\t\tt[ind]=merge(t[(ind<<1)],t[((ind<<1) |1)]);\n\t}\n\tvoid update( int ind , int l,int r, int pos ,int val) \n\t{ \n\t\tif(pos<l || pos>r) //then this node doesn\'t contain the range we are searching so leave it \n\t\t{ \n\t\t\treturn;\n\t\t}\n\t\tif(l==r) \n\t\t{ \n\t\t\tt[ind].x = val;//updating segment tree \n\t\t\tarr[l]=val;//updating original array if you want to \n\t\t\treturn; \n\t\t}\n\t\n\t\tint mid = l+((r-l)>>1);\n\t\tupdate((ind<<1),l,mid,pos,val );\n\t\tupdate(((ind<<1) |1),mid+1,r,pos,val);\n\t\tt[ind]=merge(t[(ind<<1)],t[((ind<<1) |1)]);\n\t\treturn;\n\t\n\t}\n\tnode querry(int ind , int l ,int r, int lq,int rq) \n\t{ \n\t\tif(l>rq || lq>r)\n\t\t{ \n\t\t\tnode z;\n\t\t\treturn z;\n\t\t}\n\t\tif(l>=lq && r<=rq) \n\t\t{ \n\t\t\treturn t[ind];//this is the ans of the range l to r \n\t\t}\n\t\t// dbg(\'a\');\n\t\tint mid = l+((r-l)>>1);\n\treturn \tmerge(querry((ind<<1),l,mid,lq,rq) ,\tquerry(((ind<<1) |1),mid+1,r,lq,rq));//isme kuch update ni karna hai isliye t[ind] wo sab use ni karenge \n\t\n\t\n\t}\n\t};\n\tint N=1e5+1;\n\tint lengthOfLIS(vector<int>& nums, int k) {\n\t\tsegtree st(N);//stores max increasing subsequence ending at element i \n\t\tst.build(1,0,N-1);\n\t\tint ans =0;\n for(int i=0;i<nums.size();i++)\n\t\t{\n\t\t\tint prev_val =st.querry(1,0,N-1,nums[i],nums[i]).x;//value which was earlier present when our subsequence was ending at nums[i]\n\t\t\tint lq = max(0ll,nums[i]-k);\n\t\t\tint rq=max(0ll,nums[i]-1);\n\t\t\tint mx_k_prev_values = st.querry(1,0,N-1,lq,rq).x;\n\t\t\tif(mx_k_prev_values+1>prev_val)\n\t\t\t{\n\t\t\t\tans =max(ans,mx_k_prev_values+1);\n\t\t\t\tst.update(1,0,N-1,nums[i],mx_k_prev_values+1ll);//updating the segment tree if we have more value than what previous value was\n\t\t\t}\n\t\t}\n\t\treturn ans;\n }\n``` | 1 | 0 | ['Dynamic Programming', 'Tree'] | 0 |
longest-increasing-subsequence-ii | Segment Tree | segment-tree-by-java_programmer_ketan-raml | \n/*\n This can be solved using a segment tree\n Time Complexity -> O(NlogN)\n Space Complexity -> O(NlogN)\n\n\n Idea-> Create a dp arr which store | Java_Programmer_Ketan | NORMAL | 2022-09-11T04:01:04.059108+00:00 | 2022-09-11T04:01:57.077198+00:00 | 240 | false | ```\n/*\n This can be solved using a segment tree\n Time Complexity -> O(NlogN)\n Space Complexity -> O(NlogN)\n\n\n Idea-> Create a dp arr which stores the length of LIS ending at that index.\n Use maximum segment tree to get maximum in range and add 1, as this number is also a part of LIS\n*/\n\n//Adding more explaination shortly\nclass Solution {\n public int lengthOfLIS(int[] nums, int k) {\n MaximumSegmentTree sg = new MaximumSegmentTree(new long[1_000_01]);\n for(int num: nums){\n int left = Math.max(0,num-k);\n int right = num-1;\n long nv = sg.getMaximumInclusiveOfRange(left,right);\n sg.update(num,nv+1);\n }\n long max=0;\n for(int i=0;i<=100000;i++) max=Math.max(max,sg.getMaximumInclusiveOfRange(i,i));\n return (int)max;\n }\n}\nclass MaximumSegmentTree{\n private int lengthOfArray;\n private long[] arr;\n private long[] segmentArray;\n private int heightOfSegmentTree;\n\n public MaximumSegmentTree(long[] a){\n this.lengthOfArray = a.length;\n this.arr = new long[lengthOfArray];\n for(int i=0;i<a.length;i++) arr[i] = a[i];\n this.heightOfSegmentTree = (int)Math.ceil(Math.log(lengthOfArray)/Math.log(2));\n int lengthOfSegmentArray = 2*(1<<heightOfSegmentTree)-1;\n this.segmentArray = new long[lengthOfSegmentArray];\n maximumSegmentTreeConstructorUtil(0,lengthOfArray-1,0);\n }\n\n private long maximumSegmentTreeConstructorUtil(int segmentStart, int segmentEnd, int segmentIndex){\n if(segmentEnd == segmentStart) return segmentArray[segmentIndex] = arr[segmentStart];\n int mid = getMid(segmentStart,segmentEnd);\n return segmentArray[segmentIndex] = Math.max(maximumSegmentTreeConstructorUtil(segmentStart,mid,segmentIndex*2+1),\n maximumSegmentTreeConstructorUtil(mid+1,segmentEnd,segmentIndex*2+2));\n }\n\n private int getMid(int segmentStart, int segmentEnd){\n return (segmentStart+segmentEnd)>>1;\n }\n\n public long getMaximumInclusiveOfRange(int left, int right){\n return getMinimumUtil(0,lengthOfArray-1,left,right,0);\n }\n private long getMinimumUtil(int segmentStart, int segmentEnd, int queryStart, int queryEnd, int segmentIndex){\n if(queryStart<=segmentStart && segmentEnd<=queryEnd) return segmentArray[segmentIndex];\n if(queryEnd<segmentStart || segmentEnd<queryStart) return -1;\n int mid = getMid(segmentStart,segmentEnd);\n return Math.max(getMinimumUtil(segmentStart,mid,queryStart,queryEnd,segmentIndex*2+1),\n getMinimumUtil(mid+1,segmentEnd,queryStart,queryEnd,segmentIndex*2+2));\n }\n public void update(int index, long value){\n updateConstructorUtil(0,lengthOfArray-1,0,index,value);\n }\n private long updateConstructorUtil(int segmentStart, int segmentEnd, int segmentIndex, int index, long newValue){\n if(index>segmentEnd || index<segmentStart) return segmentArray[segmentIndex];\n if(segmentStart==index && segmentEnd==index) return segmentArray[segmentIndex]=newValue;\n int mid = getMid(segmentStart,segmentEnd);\n return segmentArray[segmentIndex]=Math.max(updateConstructorUtil(segmentStart,mid,2*segmentIndex+1,index,newValue),\n updateConstructorUtil(mid+1,segmentEnd,2*segmentIndex+2,index,newValue));\n }\n}\n\n\n``` | 1 | 1 | [] | 0 |
longest-increasing-subsequence-ii | Segment Tree - [Point update, max in a range] || C++ | segment-tree-point-update-max-in-a-range-1qg9 | \nclass Solution {\nprivate:\n vector<int> tree;\n void pUpdate(int node,int st,int en,int pos,int val){\n if(st > pos or en < pos) return;\n\n | _Pinocchio | NORMAL | 2022-09-11T04:00:27.858036+00:00 | 2022-09-11T04:12:55.992840+00:00 | 395 | false | ```\nclass Solution {\nprivate:\n vector<int> tree;\n void pUpdate(int node,int st,int en,int pos,int val){\n if(st > pos or en < pos) return;\n\n if(st == en){\n tree[node] = max(tree[node],val);\n }else{\n int mid = st + (en - st)/2;\n pUpdate(node*2,st,mid,pos,val);\n pUpdate(node*2+1,mid+1,en,pos,val);\n tree[node] = max(tree[node*2], tree[node*2+1]);\n }\n }\n int findMax(int node,int st,int en,int l,int r){\n if(en < l or st > r) return -1e9;\n\n if(st >= l and en <= r) return tree[node];\n\n int mid = st + (en-st)/2;\n\n int left = findMax(node*2,st,mid,l,r);\n int right = findMax(node*2+1,mid+1,en,l,r);\n\n return max(left,right);\n }\npublic:\n int lengthOfLIS(vector<int>& nums, int k) {\n int mx = *max_element(nums.begin(),nums.end());\n tree.resize(4*1e5 + 2);\n for(auto i : nums){\n int maxi = findMax(1,0,mx,max(i-k,0),max(i-1,0));\n pUpdate(1,0,mx,i,1+maxi);\n }\n return tree[1];\n }\n};\n``` | 1 | 1 | ['Tree', 'C', 'C++'] | 0 |
longest-increasing-subsequence-ii | Python | python-by-g-ez-4lm6 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | G-EZ | NORMAL | 2025-03-14T00:00:59.890486+00:00 | 2025-03-14T00:00:59.890486+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python []
class Solution(object):
def lengthOfLIS(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
return lengthOfLIS(nums, k)
class SegmentTree:
def __init__(self, size):
"""Initialize the segment tree with given size."""
self.n = size
self.tree = [0] * (2 * size) # Using a 1-based indexed segment tree
def update(self, index, value):
"""Update the value at index in the segment tree."""
index += self.n # Move to leaf position
self.tree[index] = value # Update value at leaf
while index > 1:
index //= 2 # Move to parent
self.tree[index] = max(self.tree[2 * index], self.tree[2 * index + 1]) # Update parent
def query(self, left, right):
"""Query the maximum value in the range [left, right] (inclusive)."""
left += self.n # Shift to leaf level
right += self.n
max_value = 0 # Default minimum for max queries
while left <= right:
if left % 2 == 1: # If left is a right child, include it
max_value = max(max_value, self.tree[left])
left += 1
if right % 2 == 0: # If right is a left child, include it
max_value = max(max_value, self.tree[right])
right -= 1
left //= 2
right //= 2
return max_value
def lengthOfLIS(nums, k):
max_val = max(nums)
segment_tree = SegmentTree(max_val)
ans = 0
for i in range(len(nums)):
num = nums[i]
smallest = max(1, num - k)
largest = num-1
largest_count = segment_tree.query(smallest-1, largest-1)
largest_so_far = max(largest_count + 1, segment_tree.query(num-1, num-1))
segment_tree.update(num-1, largest_so_far)
ans = max(ans, largest_so_far)
return ans
``` | 0 | 0 | ['Python'] | 0 |
longest-increasing-subsequence-ii | Segment Tree | segment-tree-by-tavvfikk-5i16 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | tavvfikk | NORMAL | 2025-01-23T01:08:02.016444+00:00 | 2025-01-23T01:08:02.016444+00:00 | 31 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class SegTree
{
private:
int tree_size;
vector<int> tree;
void update(int lx, int rx, int ni, int num, int val)
{
if (rx - lx == 1)
{
tree[ni] = max(tree[ni], val);
return;
}
int m = (lx + rx) >> 1;
if (num < m)
update(lx, m, ni * 2 + 1, num, val);
else
update(m, rx, ni * 2 + 2, num, val);
tree[ni] = max(tree[ni * 2 + 1], tree[ni * 2 + 2]);
}
int query(int l, int r, int lx, int rx, int ni)
{
if (lx >= r || rx <= l)
return 0;
if (l <= lx && rx <= r)
return tree[ni];
int m = (lx + rx) >> 1;
return max(query(l, r, lx, m, ni * 2 + 1), query(l, r, m, rx, ni * 2 + 2));
}
public:
SegTree(int n)
{
tree_size = 1;
while (tree_size < n)
tree_size <<= 1;
tree = vector<int>(tree_size * 2, 0);
}
void update(int num, int val)
{
update(0, tree_size, 0, num, val);
}
int query(int l, int r)
{
return query(l, r, 0, tree_size, 0);
}
};
class Solution
{
public:
int lengthOfLIS(vector<int> &nums, int k)
{
int n = nums.size();
int max_val = *max_element(nums.begin(), nums.end());
SegTree seg_tree(max_val + 1);
for (const auto &num : nums)
{
int l = max(0, num - k), r = num - 1;
int LIS = seg_tree.query(l, r + 1);
seg_tree.update(num, LIS + 1);
}
return seg_tree.query(0, max_val + 1);
}
};
``` | 0 | 0 | ['Segment Tree', 'C++'] | 0 |
longest-increasing-subsequence-ii | Simple Seg Tree | simple-seg-tree-by-rahulsaini1234-kbws | IntuitionMax range queries Segment Tree
Focus on values of nums[i].ApproachComplexity
Time complexity:
O(nlogn)
Space complexity:
O(n)Code | rahulsaini1234 | NORMAL | 2025-01-06T14:52:17.561234+00:00 | 2025-01-06T14:52:17.561234+00:00 | 12 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Max range queries Segment Tree
Focus on values of nums[i].
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(nlogn)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(n)
# Code
```java []
class Solution {
public class SegTree{
int[] seg;
int n;
SegTree(int n){
this.n = n;
seg = new int[4 * n];
}
private void update(int node, int st, int end, int idx, int val){
if(idx < st || idx > end)return;
if(st == end){
seg[node] = val;
return;
}
int mid = (st + end) / 2;
update(2 * node + 1, st, mid, idx, val);
update(2 * node + 2, mid + 1, end, idx, val);
seg[node] = Math.max(seg[2 * node + 1], seg[2 * node + 2]);
}
public void updatetree(int idx, int val){
update(0,0,n - 1, idx, val);
}
private int query(int node, int st, int end, int l, int r){
if(st > r || end < l) return 0;
if(l <= st && r >= end) return seg[node];
int mid = (st + end) / 2;
return Math.max(query(2 * node + 1, st, mid, l, r), query(2 * node + 2, mid + 1, end,l ,r));
}
public int querytree(int l, int r){
return query(0,0,n-1,l,r);
}
}
public int lengthOfLIS(int[] a, int k) {
int n = a.length;
int max= 1;
for(int x : a) max = Math.max(x, max);
SegTree seg = new SegTree(max + 1);
int ans = 1;
for(int x : a){
int q = seg.querytree(Math.max(1, x - k), x - 1);
ans = Math.max(ans, q + 1);
seg.updatetree(x, q + 1);
}
return ans;
}
}
``` | 0 | 0 | ['Java'] | 0 |
longest-increasing-subsequence-ii | Segment tree with point update | segment-tree-with-point-update-by-joshit-80wo | Code | joshithmurthy | NORMAL | 2025-01-04T18:33:27.136551+00:00 | 2025-01-04T18:33:27.136551+00:00 | 12 | false |
# Code
```cpp []
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;
class Solution {
public:
void pointUpdate(vector<int>& tree, int node, int start, int end, int idx, int val) {
if (start == end) {
tree[node] = max(tree[node], val); // Update with max value
} else {
int mid = start + (end - start) / 2;
if (idx <= mid) {
pointUpdate(tree, 2 * node, start, mid, idx, val);
} else {
pointUpdate(tree, 2 * node + 1, mid + 1, end, idx, val);
}
tree[node] = max(tree[2 * node], tree[2 * node + 1]);
}
}
int query(vector<int>& tree, int node, int start, int end, int l, int r) {
if (r < start || end < l) {
return 0; // Outside the range, return minimum for max query
}
if (l <= start && end <= r) {
return tree[node]; // Completely inside the range
}
int mid = start + (end - start) / 2;
int left = query(tree, 2 * node, start, mid, l, r);
int right = query(tree, 2 * node + 1, mid + 1, end, l, r);
return max(left, right);
}
int lengthOfLIS(vector<int>& nums, int k) {
if (nums.empty()) return 0;
int n = 100005; // Assume nums[i] are within [1, 100000]
vector<int> tree(4 * n, 0); // Segment tree for range [1, n]
int ans = 1;
for (int i = nums.size() - 1; i >= 0; i--) {
// Query the maximum length of subsequence in range [nums[i] + 1, nums[i] + k]
int q = query(tree, 1, 1, n, nums[i] + 1, min(n, nums[i] + k));
ans = max(ans, q + 1);
// Update the segment tree with the new maximum length for nums[i]
pointUpdate(tree, 1, 1, n, nums[i], q + 1);
}
return ans;
}
};
``` | 0 | 0 | ['C++'] | 0 |
longest-increasing-subsequence-ii | C++ Segment Tree (Simple Code) | c-segment-tree-simple-code-by-yz19b-exzo | This is the hardest problem I've seen on Leetcode!Not only on dynamical programming, segment tree, but also on be clear about mananging index.IntuitionDynamical | yz19b | NORMAL | 2025-01-04T06:05:43.357604+00:00 | 2025-01-04T06:05:43.357604+00:00 | 19 | false | This is the hardest problem I've seen on Leetcode!
Not only on dynamical programming, segment tree, but also on be clear about mananging index.
# Intuition
### Dynamical Programming
Finding dynamical programming for this problem is not very hard:
Define: dp[i]: the length of longest subarray in the first i-1 element
Then:
$$
dp[nums[i]] = dp[nums[i-1]] + max\{dp[nums[i]-k], ..., dp[nums[i]-1]\}
$$
Be careful here: since c++ does not support 1-based array, but the dp we wrote above is a **1-based array**, to avoid problem in later steps, it is better to write it as
$$
dp[nums[i]-1] = 1 + max \{dp[nums[i]-k-1,...,dp[nums[i]-2]\}
$$
The first index issue comes: $nums[i]-2$
if $num[i]=1$, $nums[i]-2=-1$. Some people might think what about using $max(0,nums[i]-2)$. This will cause accumulation of dp[0] for dp[0]. If nums has multiplt 1's, you will have issue. So we need to check $nums[i]-2$ when we do dp, if $nums[i]-2<0$, then $dp[nums[i]-1] = 1 + 0$.
In addition, the size of dp is max value in nums. let's call $maxnum$
### Segement Tree
we might just do a double for loop with DP to solve it, but time complexity is O(n^2). To optimize it to O(nlogn), we can utilize segement tree
The tree node store the maximum dp value within dp[start] to dp[end]. By using divide and conqur, we can divide [0,maxnum-1] into nodes
And we use a vector (size: 4*maxnum) to store segement tree Node.
Take an example [1 3 2 5 7 9]:
dp size is 9, so the segement tree corresponds to range [0,8]

For each node, I put the index of this node in an array at left
and index range of dp where the node value is obtained at right
##### Update Tree
From top to bottom, we start search by using divide and conqur to find the leaf node where the index $nums[i]-1$ of dp was stored, then we update node value, for example, nums[i]=3,
$$node[8] = dp[2]$$
then backsteping help us to update all internal nodes by using
$$node[i] = node[2*i+1](left child) + node[2*i+2](right child)$$
Then the question is how would we know dp[2] in above example. Of course, through dynamical programming. $max \{dp[nums[i]-k-1,...,dp[nums[i]-2]\}$ can be queried from the segment tree
##### Query Tree
Given a range $[nums[i]-k-1, nums[i]-2]$, we need to know the max dp value. Still use the example $nums[i]=3$, and $k=2$, so the range we want to query is $[0,1]$. We start from top, it is inside its range [0,8], so ...
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
O(nlogn)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(4*10^5) = O(1)
# Code
```cpp []
class Solution {
void updatetree(vector<int>& tree, int node, int start, int end, int idx, int value){
// leaf node
if(start==end){
tree[node] = max(tree[node],value);
return;
}
// divide and conque
int mid = (start+end)/2;
if(idx<=mid){
updatetree(tree, 2*node+1, start, mid, idx, value); // left child
}else{
updatetree(tree, 2*node+2, mid+1, end, idx, value); // right child
}
// add value to tree node
tree[node] = max(tree[2*node+1],tree[2*node+2]);
}
int querytree(const vector<int>& tree, int node, int start, int end, int left, int right){
// start, end: start and end index of the current treenode
// left, right: queried left and right index
// if not in the range of the node, return integer min
if(start>right || end<left){
return 0;
}
if(left<=start && end<=right){
return tree[node];
}
int mid = (start+end)/2;
// otherwise, compare the left and right child
int leftmax = querytree(tree, node*2+1,start,mid,left,right);
int rightmax = querytree(tree, node*2+2, mid+1, end, left,right);
return max(leftmax, rightmax);
}
public:
// dp[i] = 1+max{dp[i-1],dp[i-2],...,dp[i-k]}
int lengthOfLIS(vector<int>& nums, int k) {
// if(nums.size()==1){
// return 1;
// }
int n = nums.size();
// find the max value in nums, and then formulate the vector dp (which represent segment tree) with the max value as the size O(n)n
int maxnum = INT_MIN;
for(auto num: nums){
maxnum = max(num,maxnum);
}
vector<int> tree(maxnum*4, 0);
vector<int> dp(maxnum, 0);
// queue (traverse tree) O(nlogn)
int maxlen =1;
for(int i=0; i<nums.size();i++){
if(nums[i]-2<0){
dp[nums[i]-1] = 1;
}else{
dp[nums[i]-1] = 1+querytree(tree,0,0,maxnum-1,max(0, nums[i] - k-1),nums[i]-2);
}
maxlen = max(maxlen,dp[nums[i]-1]);
updatetree(tree, 0, 0, maxnum-1, nums[i]-1, dp[nums[i]-1]);
}
return maxlen;
}
};
``` | 0 | 0 | ['C++'] | 0 |
longest-increasing-subsequence-ii | Javascript Segment Tree O(n * log(max(n)) time, O(max(n)) space | javascript-segment-tree-on-logmaxn-time-fvdqr | IntuitionFor any value in nums, we can store the Longest Increasing Subsequence (LIS) ending at that value within a segment tree. As we iterate over nums, we ca | alexdovzhanyn | NORMAL | 2025-01-02T00:01:53.880601+00:00 | 2025-01-02T00:01:53.880601+00:00 | 4 | false | # Intuition
For any value in nums, we can store the Longest Increasing Subsequence (LIS) ending at that value within a segment tree. As we iterate over nums, we can efficiently find the maximum LIS of any numbers that the current nums[i] would be a valid next number for. This is any number in the range [n - k, n - 1], since we can't have a difference greater than k between subsequent numbers, and we can't use the same number twice in a subsequence.
# Approach
1. Find the max value in the nums array. This takes O(n) time.
2. Create a segment tree containing all possible values from 0..maxValue. This is O(maxVal) time.
3. For each num in nums, we find the LIS of the range of numbers that the num could be a next num for, and add 1 to it (since this would be the next num in the sequence). Then we update the segment tree at node num to store the LIS ending at that num. This step takes O(n) to iterate through the whole array, and performs 2 O(log(maxVal)) operations per iteration. Therefore this step is O(n * log(maxVal)) time.
4. Potentially update the maxLength at each step in the iteration
5. Return maxLength after we've iterated through all nums in n
# Complexity
- Time complexity: $$O(n * log(maxVal))$$
Step 3 dominates our time complexity here.
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(maxVal)$$
We store approximately 2 * maxVal nodes in the segment tree, which simplifies to $$O(maxVal)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```javascript []
class SegmentTree {
constructor(l, r) {
this.l = l
this.r = r
if (l == r) {
// Initialize all to zero
this.val = 0
return
}
const mid = Math.floor((l + r) / 2)
this.mid = mid
this.left = new SegmentTree(l, mid)
this.right = new SegmentTree(mid + 1, r)
this.val = Math.max(this.left.val, this.right.val)
}
find(l, r) {
// No overlap
if (l > this.r || r < this.l) return 0
// Total overlap
if (l <= this.l && r >= this.r) return this.val
// Entirely in left subtree
if (r <= this.mid) return this.left.find(l, r)
// Entirely in right subtree
if (l > this.mid) return this.right.find(l, r)
// Spans across both subtrees
return Math.max(this.left.find(l, this.mid), this.right.find(this.mid + 1, r))
}
update(i, val) {
if (i > this.r || i < this.l) return
if (this.l == this.r) {
this.val = val
return
}
if (i <= this.mid) {
this.left.update(i, val)
} else {
this.right.update(i, val)
}
this.val = Math.max(this.left.val, this.right.val)
}
}
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var lengthOfLIS = function(nums, k) {
const maxVal = Math.max(...nums)
const sTree = new SegmentTree(0, maxVal)
let max = 0
for (const num of nums) {
const lis = sTree.find(Math.max(1, num - k), num - 1)
sTree.update(num, lis + 1)
max = Math.max(max, lis + 1)
}
return max
};
``` | 0 | 0 | ['Segment Tree', 'JavaScript'] | 0 |
longest-increasing-subsequence-ii | C++ Segment Tree | c-segment-tree-by-kimcuong09102004-5lcr | IntuitionApproachComplexity
Time complexity: O(nlogn)
Space complexity:
Code | kimcuong09102004 | NORMAL | 2024-12-14T10:10:45.106217+00:00 | 2024-12-14T10:10:45.106217+00:00 | 15 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$ O(nlogn) $$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int getmax(const vector<int>& tree, int id, int l, int r, int i, int j)\n {\n if (i <= l && r <= j) return tree[id];\n if (i > r || j < l) return INT_MIN;\n int m = (l + r) / 2;\n int maxleft = getmax(tree, 2 * id, l, m, i, j);\n int maxright = getmax(tree, 2 * id + 1, m + 1, r, i, j);\n return max(maxleft, maxright);\n }\n void update(vector<int>& tree, int id, int l, int r, int pos, int val)\n {\n // cout << "updating: " << endl;\n // cout << "id: " << id << endl;\n // cout << "l: " << l << endl;\n // cout << "r: " << r << endl;\n // cout << "pos: " << pos << endl;\n // cout << "val: " << val << endl;\n if (pos > r || pos < l) return;\n if (l == r)\n {\n tree[id] = val;\n return;\n }\n int m = (l + r) / 2;\n update(tree, 2 * id, l, m, pos, val);\n update(tree, 2 * id + 1, m + 1, r, pos, val);\n tree[id] = max(tree[2 * id], tree[2 * id + 1]);\n }\n int solve(const vector<int>& nums, int k)\n {\n int n = nums.size();\n int maxnum = INT_MIN;\n for (auto num : nums) maxnum = max(maxnum, num);\n vector<int> tree(4 * maxnum + 1, 0);\n vector<int> dp(n, 1);\n int res = 1;\n for (int i = 0; i < n; i++)\n {\n if (nums[i] == 1)\n {\n dp[i] = 1;\n update(tree, 1, 1, maxnum, nums[i], dp[i]);\n continue;\n }\n int start = max(nums[i] - k, 1);\n int end = nums[i] - 1;\n int maxleft = getmax(tree, 1, 1, maxnum, start, end);\n //cout << maxleft << endl;\n dp[i] = maxleft + 1;\n update(tree, 1, 1, maxnum, nums[i], dp[i]);\n res = max(res, dp[i]);\n }\n return res;\n }\n int lengthOfLIS(vector<int>& nums, int k) {\n return solve(nums, k);\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
longest-increasing-subsequence-ii | Descriptive Explanation of DP to Segment Tree Optimization | descriptive-explanation-of-dp-to-segment-vwrx | null | diaalrahman312 | NORMAL | 2024-12-12T06:58:43.759599+00:00 | 2024-12-12T06:58:43.759599+00:00 | 25 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nRun the tabular approach first, and make sure to activate the print statement. This will help you visualise what\'s going on. The segment tree is just a handy data structure that helps in optimizing in range related questions. Use it instead of an array when it\'s possible to travel in a binary search way.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nEssentially, because we don\'t have to build the path itself, and only the length, it\'s possible to build an algorithm that only keeps track of the length and nothing else. \n\nWith the tabular approach, you first build an empty array with a size of max(nums), and initilize everything to zero. \'n\' is the current value in the subsequent explanation. Then as you traverse nums, grab the max value in the range (n - k to n - 1) of the table. Add one to this, which will be the new valid path including the current value. \n\nSo, for [5] we would grab values for [2], [3] and [4] from the table, and the max of that would be a valid path to 5, so we add 1 to this max value. Compare it to the current table value for [5], and update accordingly.\n\nNow, because you are looking over a range for every single element in the nums array, it\'s possible to optimize the solution by using a segement tree instead where each range holds the max value (instead of typically applied sum). This way at the end of the traversal the maximum length bubbles to the root node which can be returned.\n\nBuild a tree that will occupy the max values in the range (0 to max(nums)). Call query on the range (n -k, n - 1), as well as on the range(n, n) where n is the current value. Compare these values and update for (n, n) in the segment tree.\n\nThis is easier to visualise on paper, so I suggest you draw out the tree and dry run by hand. Once you have a strong visualisation, the code should come to your mind automatically or at least be able to understand the code that others wrote.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity for the tabular approach is O(nk), and with the segment tree it\'s O(n log max(nums)). In the tabular approach, with each number we have to grab k values each time, and for k -> n, the time complexity can reach up to O(n ^ 2). \n\nWith the second approach, a better time complexity is achieved because each query and update call is a O(log max(nums)), as log max(nums) is the height of the tree.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity should be O(max(nums)) for storing the ranges in the segment tree. This is because the tree has the individual (self.L == self.R) nodes for each value in (0 to max(nums)).\n# Code\n```python3 []\nclass SegmentTree:\n def __init__(self, max_val, l, r):\n self.max_val = max_val\n self.L, self.R = l, r\n self.left, self.right = None, None\n\n @staticmethod\n def build_tree(l, r):\n if l == r:\n return SegmentTree(0, l, r)\n m = l + (r - l) // 2\n root = SegmentTree(0, l, r)\n root.left = SegmentTree.build_tree(l, m)\n root.right = SegmentTree.build_tree(m + 1, r)\n root.max_val = max(root.left.max_val, root.right.max_val)\n return root\n\n def query(self, l, r):\n if self.L == l and self.R == r:\n # print(self.L, self.R, self.max_val)\n return self.max_val\n m = self.L + (self.R - self.L) // 2\n if l > m:\n return self.right.query(l, r)\n elif r <= m:\n return self.left.query(l, r)\n else:\n return max(self.left.query(l, m), self.right.query(m + 1, r))\n \n def update(self, new_val, pos):\n if self.L == self.R:\n self.max_val = new_val\n return\n m = self.L + (self.R - self.L) // 2\n if pos > m:\n self.right.update(new_val, pos)\n elif pos <= m:\n self.left.update(new_val, pos)\n self.max_val = max(self.right.max_val, self.left.max_val)\n return\n\nclass Solution:\n def lengthOfLIS(self, nums: List[int], k: int) -> int:\n # max_lens = [0] * (max(nums) + 1)\n # for n in nums:\n # min_val = max(0, n - k)\n # seq_len = max(max_lens[min_val:n]) + 1\n # max_lens[n] = max(seq_len, max_lens[n])\n # # print(max_lens, n)\n \n # return max(max_lens)\n max_lens = SegmentTree.build_tree(0, max(nums))\n for n in nums:\n min_val, max_val = max(0, n - k), max(0, n - 1)\n seq_len = max_lens.query(min_val, max_val) + 1\n curr_len = max_lens.query(n, n)\n # print("seq_len", seq_len, min_val, max_val)\n # print("curr_len", curr_len, n)\n max_lens.update(max(seq_len, curr_len), n)\n \n return max_lens.query(0, max(nums))\n``` | 0 | 0 | ['Divide and Conquer', 'Dynamic Programming', 'Segment Tree', 'Python', 'Python3'] | 0 |
longest-increasing-subsequence-ii | GPT is really helpful | gpt-is-really-helpful-by-parthtiwari96-5qr0 | Intuition\nSolving it with segment tree was understood, since I had the same idea using the normal LCI problem.\n\n# Approach\nI asked GPT with very basic promp | parthtiwari96 | NORMAL | 2024-12-05T16:33:31.948471+00:00 | 2024-12-05T16:33:31.948513+00:00 | 24 | false | # Intuition\nSolving it with segment tree was understood, since I had the same idea using the normal LCI problem.\n\n# Approach\nI asked GPT with very basic prompt.\nPlease refer here.\nhttps://chatgpt.com/share/6751d421-5d68-8004-8242-aaa3b0aa9653\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(nlogn)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\n#include <vector>\n#include <algorithm>\n#include <functional>\nusing namespace std;\n\nclass Solution {\npublic:\n int lengthOfLIS(vector<int>& nums, int k) {\n int maxVal = *max_element(nums.begin(), nums.end());\n vector<int> segTree(4 * (maxVal + 1), 0); // Segment tree for range maximum queries\n\n // Use std::function to allow recursive lambda\n function<int(int, int, int, int, int)> query = [&](int node, int start, int end, int l, int r) -> int {\n if (r < start || end < l) {\n return 0; // Out of range\n }\n if (l <= start && end <= r) {\n return segTree[node]; // Fully within range\n }\n int mid = (start + end) / 2;\n int leftQuery = query(2 * node + 1, start, mid, l, r);\n int rightQuery = query(2 * node + 2, mid + 1, end, l, r);\n return max(leftQuery, rightQuery); // Combine results\n };\n\n // Update function\n function<void(int, int, int, int, int)> update = [&](int node, int start, int end, int idx, int value) {\n if (start == end) {\n segTree[node] = max(segTree[node], value); // Update leaf node\n return;\n }\n int mid = (start + end) / 2;\n if (idx <= mid) {\n update(2 * node + 1, start, mid, idx, value);\n } else {\n update(2 * node + 2, mid + 1, end, idx, value);\n }\n segTree[node] = max(segTree[2 * node + 1], segTree[2 * node + 2]); // Update parent\n };\n\n int maxLength = 0;\n\n for (int num : nums) {\n // Query the range [num - k, num - 1]\n int maxPrev = query(0, 0, maxVal, max(0, num - k), num - 1);\n int currentLen = maxPrev + 1; // Extend the subsequence with the current element\n update(0, 0, maxVal, num, currentLen); // Update the segment tree\n maxLength = max(maxLength, currentLen); // Track the overall maximum\n }\n\n return maxLength;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
longest-increasing-subsequence-ii | Classic Segment Tree - Max Value | classic-segment-tree-max-value-by-deydev-49gh | DP - Time Limit Exceeded\nPython []\nclass Solution:\n # O(n^2) time | O(n) space\n def lengthOfLIS(self, nums: List[int], k: int) -> int:\n n = le | deydev | NORMAL | 2024-11-30T10:48:10.867991+00:00 | 2024-11-30T10:52:29.037838+00:00 | 11 | false | # DP - Time Limit Exceeded\n``` Python []\nclass Solution:\n # O(n^2) time | O(n) space\n def lengthOfLIS(self, nums: List[int], k: int) -> int:\n n = len(nums)\n dp = [1] * n\n best_streak = 1\n\n for i in range(n):\n for j in range(i - 1, -1, -1):\n if 1 <= nums[i] - nums[j] <= k and dp[j] + 1 > dp[i]:\n dp[i] = dp[j] + 1\n best_streak = max(best_streak, dp[i])\n return best_streak\n```\n\n---\n\nIn DP solution, the computational heavy part is the nested for loop.\n\nWhich is trying to find the `max DP value` for previous calculations. We are only considering numbers over the range `[nums[i]-k, nums[i]-1]`.\n\n\nSome Observations\n- Strictly increasing subsequence, means every number in subsequence we\'re trying to concat with is **distinct**\n- We can optimize the search for `max DP value` over the range `[nums[i]-k, nums[i]-1]` by using a Segement Tree as our "dp cache".\n\n---\n\n# Segment Tree - Range Max \nEssentially storing DP results in Segment tree.\n\n```python []\nclass SegmentTree:\n # O(m) time | O(m) space\n def __init__(self, n):\n # intialize as no LIS ending at any number\n self.tree = [0] * 4 * n\n self.n = n\n\n # O(logm) time | O(m) space\n def query(self, query_start, query_end):\n return self.__query(1, 0, self.n - 1, query_start, query_end)\n\n def __query(self, node, seg_start, seg_end, query_start, query_end):\n if query_end < seg_start or seg_end < query_start:\n # no overlap\n return 0\n if query_start <= seg_start and seg_end <= query_end:\n # full overlap\n return self.tree[node]\n # partial overlap\n mid = (seg_start + seg_end) // 2\n left_node, right_node = node * 2, node * 2 + 1\n left_max = self.__query(left_node, seg_start, mid, query_start, query_end)\n right_max = self.__query(right_node, mid + 1, seg_end, query_start, query_end)\n return max(left_max, right_max)\n\n # O(logm) time | O(m) space\n def update(self, index, new_value):\n return self.__update(1, 0, self.n - 1, index, new_value)\n\n def __update(self, node, seg_start, seg_end, index, new_value):\n if seg_start == seg_end:\n self.tree[node] = new_value\n return\n mid = (seg_start + seg_end) // 2\n left_node, right_node = node * 2, node * 2 + 1\n if index <= mid:\n self.__update(left_node, seg_start, mid, index, new_value)\n else:\n self.__update(right_node, mid + 1, seg_end, index, new_value)\n self.tree[node] = max(self.tree[left_node], self.tree[right_node])\n\n\nclass Solution:\n # O(nlogm) time | O(m) space\n # n = length of nums\n # m = max value in nums\n def lengthOfLIS(self, nums: List[int], k: int) -> int:\n max_num = max(nums)\n st = SegmentTree(max_num + 1)\n\n best_streak = 1\n for val in nums:\n query_start, query_end = val - k, val - 1\n previous_lis = st.query(query_start, query_end)\n current_lis = previous_lis + 1\n st.update(val, current_lis)\n best_streak = max(best_streak, current_lis)\n\n return best_streak\n\n``` | 0 | 0 | ['Array', 'Dynamic Programming', 'Segment Tree', 'Python3'] | 0 |
longest-increasing-subsequence-ii | ✅ [JS/Rust] DP + Segment Tree Approach w/ explanation 🔥 | jsrust-dp-segment-tree-approach-w-explan-sgo1 | \uD83D\uDC4D If you found my solution to be beneficial, I would be most grateful if you would consider \u261D\uFE0FUPVOTING IT\u261D\uFE0F. This action would se | ad0x99 | NORMAL | 2024-11-20T12:23:41.496081+00:00 | 2024-11-20T12:23:41.496106+00:00 | 10 | false | **\uD83D\uDC4D If you found my solution to be beneficial, I would be most grateful if you would consider \u261D\uFE0FUPVOTING IT\u261D\uFE0F. This action would serve as a significant motivation for me to continue providing additional solutions in the future. \uD83D\uDE46\u200D\u2642\uFE0F**\n\n---\n\n# Dynamic Programming Approach (TLE)\n\n**Idea**: An increasing subsequence is a sequence where each element is greater than the one before it. The idea is as long as there are elements that are greater than the one before it, we calculate its length.\n\n**Implementation**\n\n1. We create a array which is called `dp` to store the lengths of the LIS ending at each index in the nums array.\n\n2. The outer loop iterates through each element (`nums[i]`) in the nums array. For each element, we will check if it can extend an existing LIS.\n\n3. The inner loop iterates through all elements before the current element i (0 to i-1), and we compare the elements at indices `i` and `j` to see if they can form an increasing subsequence.\n - 3.1: If the current number is greater than previous one (`nums[j] < nums[i]`). This ensures the element at index j is strictly less than the element at index i.\n\n - 3.1: And if `dp[i] < dp[j] + 1`: This checks if the length of the LIS ending at index i is less than the length of the LIS ending at index j plus 1.\n\n - 3.2: And if the difference between 2 elements is less than or equal to `k`. This ensures the difference between 2 increasing numbers is at most `k`.\n\n - 3.2: If those conditions are true, it means we can potentially extend the LIS ending at index j by including the element `nums[i]`. Therefore, the value in `dp[i]` is updated to `dp[j] + 1`, representing the new length of the LIS ending at index `i`.\n\n4. After iterating through all elements, the `dp` array holds the lengths of the LIS ending at each index. We return the maximum value in the `dp` array, which represents the length of the longest increasing subsequence in the original nums array.\n\n\n# Complexity\n- Time complexity: `O(n ^ 2)` - because we have nested-loop to find the LIS\n\n- Space complexity: `O(n)` - where `n` is the length of the `dp` array.\n\n# Code\n\n```javascript []\nconst lengthOfLIS = (nums, k) => {\n const dp = new Array(nums.length).fill(1);\n\n for (let i = 0; i < nums.length; i++) {\n for (let j = 0; j < i; j++) {\n // If the current number is greater than the previous number\n // And, if current LIS is less than previous one\n // And the difference between 2 numbers is at most k\n if (nums[i] > nums[j] && dp[i] < dp[j] + 1 && nums[i] - nums[j] <= k) {\n // Extend the previous LIS to the current LIS\n dp[i] = dp[j] + 1;\n }\n }\n }\n\n return Math.max(...dp);\n};\n```\n```rust []\nimpl Solution {\n pub fn length_of_lis(nums: Vec<i32>, k: i32) -> i32 {\n if nums.is_empty() {\n return 0;\n }\n\n let mut dp = vec![1; nums.len()];\n for i in 0..nums.len() {\n for j in 0..i {\n // If the current number is greater than the previous number\n // And, if current LIS is less than previous one\n // And the difference between 2 numbers is at most k\n if nums[i] > nums[j] && dp[i] < dp[j] + 1 && nums[i] - nums[j] <= k {\n // Extend the previous LIS to the current LIS\n dp[i] = dp[j] + 1\n }\n }\n }\n\n *dp.iter().max().unwrap()\n }\n}\n```\n\n---\n\n# Segment Tree Approach\n\n**Idea**: Each node in the Segment Tree stores the maximum LIS length for a specific range of numbers.\n\nLeaf Nodes:\n\n- Correspond to individual numbers.\n- A leaf node at index `num` represents the LIS length ending at the number `num`.\n\nParent Nodes:\n\n- Correspond to a range of numbers.\n- For example, an internal node might represent the range [1,10] and store the maximum LIS length among all numbers in that range.\n- It combines results from its child nodes: the left child for [1,5] and the right child for [6,10]\n\n**Query: Find the maximum LIS length in the range [num\u2212k, num\u22121].**\n\nWe start from the root, which represents the range [1, maxVal] and recursively check:\n- If the current node\u2019s range is outside the query range, return 0 (no contribution\n- If the current node\u2019s range is fully within the query range, return its stored value.\n- If the current node\u2019s range is partially within the query range, split into left and right children and combine their results with the maximum value.\n\n**Update: Update the LIS length for the number num.**\n\nWe start from the root, which represents the range [1, maxVal] and recursively find the leaf node corresponding to num and update its value. After updating the leaf node:\n- Recompute the parent node\u2019s value as Math.max(leftChild, rightChild).\n- Propagate this change up the tree.\n\n**What `[num \u2212 k, num \u2212 1]` represents?**\n\n- Start of the Range (num \u2212 k) represents the smallest number that can appear before `num` in a valid subsequence while respecting the constraint `num \u2212 previous <= k`.\n\n- End of the Range (num \u2212 1) indicates that only numbers strictly less than `num` can contribute to an increasing subsequence, so the range ends at `num - 1`.\n\n\n# Complexity\n- Time complexity: `O(n log n)`, where `n` is the number of elements in `nums`.\n\n- Space complexity: `O(n)`, where `n` is the size of the `tree`.\n\n# Code\n\n```javascript []\nclass SegmentTree {\n constructor(size) {\n this.tree = new Array(4 * size).fill(0);\n }\n\n query(left, right, index, leftQuery, rightQuery) {\n // If the current node\'s range is outside the query range\n if (left > rightQuery || right < leftQuery) return 0;\n\n // If the current node\'s range is completely within the query range\n if (left >= leftQuery && right <= rightQuery) {\n return this.tree[index];\n }\n\n const mid = Math.floor((left + right) / 2);\n const leftResult = this.query(\n left,\n mid,\n 2 * index + 1,\n leftQuery,\n rightQuery\n );\n const rightResult = this.query(\n mid + 1,\n right,\n 2 * index + 2,\n leftQuery,\n rightQuery\n );\n\n return Math.max(leftResult, rightResult);\n }\n\n update(left, right, nodeIdx, targetIndex, value) {\n // If the position is outside the current node\'s range\n if (targetIndex < left || targetIndex > right) return;\n\n // If the position is exactly this node\'s range\n if (left === right) {\n this.tree[nodeIdx] = Math.max(this.tree[nodeIdx], value);\n return;\n }\n\n const mid = Math.floor((left + right) / 2);\n if (targetIndex <= mid) {\n this.update(left, mid, 2 * nodeIdx + 1, targetIndex, value);\n } else {\n this.update(mid + 1, right, 2 * nodeIdx + 2, targetIndex, value);\n }\n\n // Update the parent node with the maximum of its children\n this.tree[nodeIdx] = Math.max(\n this.tree[2 * nodeIdx + 1],\n this.tree[2 * nodeIdx + 2]\n );\n }\n}\n\nconst lengthOfLIS = (nums, k) => {\n const maxVal = Math.max(...nums);\n const segmentTree = new SegmentTree(maxVal);\n let ans = 0;\n\n for (const num of nums) {\n // Query the maximum length of a subsequence ending in the range [num - k, num - 1]\n const left = Math.max(1, num - k); // Ensure the range is valid\n const right = num - 1;\n const longestSubsequence = segmentTree.query(1, maxVal, 0, left, right);\n\n // Update the segment tree with the new length for the current value\n segmentTree.update(1, maxVal, 0, num, longestSubsequence + 1);\n\n // Track the overall maximum length\n ans = Math.max(ans, longestSubsequence + 1);\n }\n\n return ans;\n};\n```\n```rust []\nstruct SegmentTree {\n tree: Vec<i32>,\n}\n\nimpl SegmentTree {\n pub fn new(size: usize) -> Self {\n SegmentTree {\n tree: vec![0; 4 * size],\n }\n }\n\n pub fn query(\n &self,\n left: usize,\n right: usize,\n index: usize,\n left_query: usize,\n right_query: usize,\n ) -> i32 {\n // If the current range is outside the query range\n if left > right_query || right < left_query {\n return 0;\n }\n\n // If the current range is completely within the query range\n if left >= left_query && right <= right_query {\n return self.tree[index];\n }\n\n let mid = (left + right) / 2;\n let left_result = self.query(left, mid, 2 * index + 1, left_query, right_query);\n let right_result = self.query(mid + 1, right, 2 * index + 2, left_query, right_query);\n\n left_result.max(right_result)\n }\n\n pub fn update(\n &mut self,\n left: usize,\n right: usize,\n index: usize,\n target_index: usize,\n value: i32,\n ) {\n // If the position is outside the current range\n if target_index < left || target_index > right {\n return;\n }\n\n // If the position matches the current range\n if left == right {\n self.tree[index] = self.tree[index].max(value);\n return;\n }\n\n let mid = (left + right) / 2;\n if target_index <= mid {\n self.update(left, mid, 2 * index + 1, target_index, value);\n } else {\n self.update(mid + 1, right, 2 * index + 2, target_index, value);\n }\n\n // Update the parent node with the maximum of its children\n self.tree[index] = self.tree[2 * index + 1].max(self.tree[2 * index + 2]);\n }\n}\n\nimpl Solution {\n pub fn length_of_lis(nums: Vec<i32>, k: i32) -> i32 {\n // Find the maximum value in nums for the range of the segment tree\n let max_val = *nums.iter().max().unwrap() as usize;\n let mut segment_tree = SegmentTree::new(max_val);\n let mut ans = 0;\n\n for &num in &nums {\n // Query the maximum LIS length in the range [num - k, num - 1]\n let left = (num - k).max(1) as usize; // Ensure the range starts at 1\n let right = (num - 1) as usize;\n let longest_subsequence = segment_tree.query(1, max_val, 0, left, right);\n\n // Update the segment tree with the new LIS length for the current number\n segment_tree.update(1, max_val, 0, num as usize, longest_subsequence + 1);\n\n // Track the overall maximum LIS length\n ans = ans.max(longest_subsequence + 1);\n }\n\n ans\n }\n}\n```\n\n\n\n | 0 | 0 | ['Dynamic Programming', 'Segment Tree', 'Rust', 'JavaScript'] | 0 |
longest-increasing-subsequence-ii | Longest Increasing Subsequence 2 | longest-increasing-subsequence-2-by-naee-j770 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Naeem_ABD | NORMAL | 2024-11-19T07:05:24.099456+00:00 | 2024-11-19T07:05:24.099493+00:00 | 9 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass SegTree: \n\n def __init__(self, arr: List[int]): \n self.n = len(arr)\n self.tree = [0] * (2*self.n)\n # for i in range(2*self.n-1, 0, -1): \n # if i >= self.n: self.tree[i] = arr[i - self.n]\n # else: self.tree[i] = max(self.tree[i<<1], self.tree[i<<1|1])\n\n def query(self, lo: int, hi: int) -> int: \n ans = 0 \n lo += self.n \n hi += self.n\n while lo < hi: \n if lo & 1: \n ans = max(ans, self.tree[lo])\n lo += 1\n if hi & 1: \n hi -= 1\n ans = max(ans, self.tree[hi])\n lo >>= 1\n hi >>= 1\n return ans \n\n def update(self, i: int, val: int) -> None: \n i += self.n \n self.tree[i] = val\n while i > 1: \n self.tree[i>>1] = max(self.tree[i], self.tree[i^1])\n i >>= 1\n\nclass Solution:\n def lengthOfLIS(self, nums: List[int], k: int) -> int:\n m = max(nums)\n ans = 0 \n tree = SegTree([0] * (m+1))\n for x in nums: \n val = tree.query(max(0, x-k), x) + 1\n ans = max(ans, val)\n tree.update(x, val)\n return ans \n``` | 0 | 0 | ['Python3'] | 0 |
longest-increasing-subsequence-ii | Improved Segment Tree | C++ | solution | improved-segment-tree-c-solution-by-moha-hluk | Intuition\n###### take a look at the Solution here, I have optimized it in memory and speed, by calculating only the required space using max value each time an | mohamedsamir591195 | NORMAL | 2024-11-16T16:08:18.904131+00:00 | 2024-11-16T16:09:49.971479+00:00 | 19 | false | # Intuition\n###### take a look at the Solution [here](https://leetcode.com/problems/longest-increasing-subsequence-ii/solutions/2560010/c-segment-tree-with-illustrationexplanation/), I have optimized it in memory and speed, by calculating only the required space using max value each time and getting the power of two using bit manipulation\n##### the result is from 142.2 MB to 56.1 MB and slightly faster runtime speed\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n log(n))\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass SegmentTree{\nprivate:\n int n;\n vector<int> tree;\n\n void updateTree(int index, int val, int L, int R, int pos) {\n\n if (L == R) {\n tree[pos] = val;\n return;\n }\n\n int M = L + (R - L) / 2;\n \n if (index <= M) {\n updateTree(index, val, L, M, 2 * pos + 1);\n } else {\n updateTree(index, val, M + 1, R, 2 * pos + 2);\n }\n\n tree[pos] = max(tree[2 * pos + 1], tree[2 * pos + 2]);\n \n }\n\n int rangeQuery(int QL, int QR, int L, int R, int pos) { // Use int instead of long long\n // Out of range\n if (L > QR || R < QL) {\n return 0;\n }\n\n // Current segment is fully within query range\n if (QL <= L && R <= QR) {\n return tree[pos];\n }\n\n int M = L + (R - L) / 2;\n\n return max(\n rangeQuery(QL, QR, L, M, 2 * pos + 1), \n rangeQuery(QL, QR, M + 1, R, 2 * pos + 2) \n );\n }\n\npublic:\n \n SegmentTree(int size) : n(size) { // Initialize n in constructor\n int total_nodes = 2 * n - 1;\n tree.resize(total_nodes, 0);\n }\n\n int rangeMaxQuery(int QL, int QR){\n return rangeQuery(QL, QR, 0, n-1, 0);\n }\n\n void update(int index, int val) {\n updateTree(index, val, 0, n-1, 0);\n }\n\n int getMaxOverAll() {\n return tree[0]; // root node represent the max over the whole range\n }\n};\n\nclass Solution { \npublic:\n \n int lengthOfLIS(vector<int>& nums, int k) {\n int max_val = *max_element(nums.begin(), nums.end());\n int idx = 0;\n while ((1 << idx) < max_val) idx++;\n \n int n = (1 << idx) + 1;\n SegmentTree tree(n);\n \n for (int num: nums) {\n int LIS = tree.rangeMaxQuery(max(0, num-k), num-1);\n tree.update(num, LIS+1);\n }\n\n return tree.getMaxOverAll(); \n }\n};\n``` | 0 | 0 | ['Segment Tree', 'C++'] | 0 |
longest-increasing-subsequence-ii | [Java] Using SegmentTree | java-using-segmenttree-by-zanhd-8yn7 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nSegmentTree\n\n# Comple | zanhd | NORMAL | 2024-11-13T18:26:30.523053+00:00 | 2024-11-13T18:26:30.523078+00:00 | 13 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSegmentTree\n\n# Complexity\n- Time complexity: O(n * log n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(4 * max-number)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass SegmentTree {\n int[] st;\n int size;\n int n; //arraySize\n\n public SegmentTree(int n) {\n this.n = n;\n this.size = 4 * n + 1;\n\n st = new int[size];\n Arrays.fill(st, 0);\n }\n\n private void update(int node, int beg, int end, int i, int value) {\n if(beg > end) return;\n\n if(beg == end) {\n if(beg == i) { // do we need this ?\n st[node] = Math.max(st[node], value); //IMP\n }\n return;\n }\n\n int mid = (beg + end) / 2;\n \n if(i <= mid) update(2 * node, beg, mid, i, value);\n else update(2 * node + 1, mid + 1, end, i, value);\n\n st[node] = Math.max(st[2 * node], st[2 * node + 1]);\n }\n\n public void update(int i, int value) {\n update(1, 0, n - 1, i, value);\n }\n \n private boolean isNoOverlap(int a, int b, int c, int d) {\n return b < c || d < a;\n }\n\n private boolean isFullOverlap(int beg, int end, int i, int j) {\n return i <= beg && end <= j;\n }\n\n private int query(int node, int beg, int end, int i, int j) {\n if(beg > end) return 0;\n\n if(isNoOverlap(beg, end, i, j)) return 0;\n\n if(isFullOverlap(beg, end, i, j)) return st[node];\n\n int mid = (beg + end) / 2;\n\n int left = query(2 * node, beg, mid, i, j);\n int right = query(2 * node + 1, mid + 1, end, i, j);\n\n return Math.max(left, right);\n }\n\n public int query(int i, int j) {\n return query(1, 0, n - 1, i, j);\n }\n}\n\n\nclass Solution {\n public int lengthOfLIS(int[] a, int k) {\n int n = a.length;\n int[] dp = new int[n]; //this is just for understanding\n\n int N = (int)1e5 + 1;\n SegmentTree segmentTree = new SegmentTree(N);\n\n dp[0] = 1;\n segmentTree.update(a[0], dp[0]); //IMP : (i, value)\n\n for(int i = 1; i < n; i++) {\n int l = Math.max(0, a[i] - k);\n int r = Math.max(0, a[i] - 1);\n\n dp[i] = segmentTree.query(l, r) + 1;\n\n segmentTree.update(a[i], dp[i]);\n }\n\n int ans = 0; for(int i = 0; i < n; i++) ans = Math.max(ans, dp[i]);\n\n return ans;\n }\n}\n``` | 0 | 0 | ['Divide and Conquer', 'Segment Tree', 'Java'] | 0 |
longest-increasing-subsequence-ii | C++, O(n*log(10^5)) | c-onlog105-by-samaun37-tuzd | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | samaun37 | NORMAL | 2024-10-29T18:10:04.719046+00:00 | 2024-10-29T18:10:04.719069+00:00 | 18 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\nprivate:\n int tree[4*100002];\n void build(int par,int l,int r)\n {\n if(l == r)\n {\n tree[par] = 0; return;\n }\n int mid = (l+r)/2;\n build(2*par,l,mid); build(2*par+1,mid+1,r);\n tree[par] = max(tree[2*par],tree[2*par+1]);\n }\n int get_max(int par,int l,int r,int L,int R)\n {\n if(r<L or l>R) return 0;\n if(l>=L and r<=R) return tree[par];\n int mid = (l+r)/2;\n return max(get_max(2*par,l,mid,L,R),get_max(2*par+1,mid+1,r,L,R));\n }\n void upd(int par,int ind,int val,int l,int r)\n {\n if(l == r)\n {\n tree[par] = val; return;\n }\n int mid = (l+r)/2;\n if(l<=ind and ind<=mid) upd(2*par,ind,val,l,mid);\n else upd(2*par+1,ind,val,mid+1,r);\n tree[par] = max(tree[2*par],tree[2*par+1]);\n }\n int maxs(int l,int r)\n {\n return get_max(1,1,1e5,l,r);\n }\n void up(int ind,int val)\n {\n upd(1,ind,val,1,1e5);\n }\npublic:\n int lengthOfLIS(vector<int>& a, int k) {\n build(1,1,100000);\n int n = a.size();\n int ans = 0;\n for(int i = 0;i<n;i++){\n int L = a[i]-k;\n int best = maxs(a[i]-k,a[i]-1);\n ans = max(ans,best+1);\n up(a[i],best+1);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
longest-increasing-subsequence-ii | Minimal Code, Maximal Comments, Beats 100% | minimal-code-maximal-comments-beats-100-kjak5 | Intuition\nMultiple brute force methods require repeatedly getting the max of n or k values, and they all exceed the time limit. We can get the max of a bunch o | kitfo | NORMAL | 2024-10-27T19:51:05.530380+00:00 | 2024-10-27T19:51:05.530462+00:00 | 10 | false | # Intuition\nMultiple brute force methods require repeatedly getting the max of n or k values, and they all exceed the time limit. We can get the max of a bunch of elements more efficiently if we store them in a segment tree.\n\n# Approach\nI had a couple failed approaches. The first was to walk nums backwards. For each num, calculate the LIS (longest increasing subsequence) by considering the numbers from here to the end of nums. This required an inner loop of up to n iterations where n is the number of elements in the nums array. So time complexity was O(n ** 2). This ended in TLE (time limit exceeded).\n\n```\n def lengthOfLIS_n2(self, nums: List[int], k: int) -> int:\n len_nums = len(nums)\n lis = [1] * len_nums\n max_lis = 1 if nums else 0\n for i in range(len_nums - 1, -1, -1):\n for j in range(i + 1, len_nums):\n if nums[i] < nums[j] and nums[j] <= nums[i] + k:\n lis[i] = max(lis[i], 1 + lis[j])\n max_lis = max(max_lis, lis[i])\n return max_lis\n```\n\nThe second failed also calculated LIS gradually as we added one number at a time, but saved the values differently. Instead of saving the LIS for each index in nums, it saves the LIS in an index equal to _the value_ of the number. For that, we need an array `lis` of m elements where m is the maximum value of the numbers in the nums array.\n\nSo if nums = [4,2,1,4,3,4,5,8,15], the max value is 15. We need at least 15 placeholders. The value at index i is LIS that can be formed ending at _the value i_. So if lis[5] = 4 means that based on the nums we\'ve seen so far, the longest subsequence I can make ending with the number 5 is of length 4.\n\n```\n def lengthOfLIS_nk(self, nums: List[int], k: int) -> int:\n lis = [0] * (max(nums) + 1)\n for num in nums:\n low_bound = max(0, num - k)\n lis[num] = 1 + max(lis[low_bound:num])\n return max(lis)\n``` \n\nThis improves our runtime to O(n * k) where n is the length of nums and k is the given limit for gaps between elements of the subsequence. Although the runtime should be improved, it still ends in TLE.\n\nHowever, this forms the basis of the working approach which is almost identical. The only difference was to use a segment tree instead of an array to store our LIS values.\n\n```\n def lengthOfLIS(self, nums: List[int], k: int) -> int:\n n = max(nums)\n seg = SegmentTreeMax(n)\n for num in nums:\n low_bound = max(0, num - k)\n lis = seg.query(low_bound, num - 1)\n seg.update(num, lis + 1)\n return seg.query(1, n)\n```\n\nThe segment tree initializes all LIS values to 0 as in the previous approach. The query method finds the maximum value in the requested range. The update method sets the value of an element at a specified index and updates the internal tree to include it in the max calculations.\n\nSee more details in the commented code below. The code itself is quite short, but I added a lot of comments to make the details clear.\n\n# Complexity\n- Time complexity:\nO(n log m) where n is the number of nums and m is the maximum value in nums.\n\n- Space complexity:\nO(m) where m is the maximum _value_ in the nums array.\n\n# Code\n```python3 []\nclass SegmentTreeMax:\n """\n This segment tree functions as an array that allows you to quickly find\n the max values in an index range.\n """\n\n def __init__(self, max_index):\n """\n Initializes a segment tree that allows you to index values from 0 to\n max_index inclusive. So if max_index=15, you can update and query\n elements in the range 0-15.\n """\n \n self.n = max_index + 1 # Add one to avoid 0-indexing\n\n # Use an array to store the tree where the individual elements are the\n # leaf nodes at positions n to n * 2 - 1, the parent of each index i\n # is at i // 2, and the left and right children of i are i * 2 and\n # i * 2 + 1 respectively.\n self.tree = [0] * self.n * 2\n \n def update(self, i, val):\n """Sets element at logical index i to val."""\n\n i += self.n\n self.tree[i] = val\n\n # Update the parent nodes to reflect the new max.\n while i > 1:\n i //= 2 # Set i to its parent index\n new_val = max(\n self.tree[i * 2], # Left child\n self.tree[i * 2 + 1], # Right child\n )\n if new_val == self.tree[i]:\n break\n self.tree[i] = new_val\n \n def query(self, low, high):\n """Finds the max value of elements from index low to high inclusive."""\n\n low, high = low + self.n, high + self.n\n max_val = float(\'-inf\')\n while low <= high:\n # If low is a right child, take its max now, then get out of this\n # subtree to avoid its sibling which we do not want.\n if low & 1:\n max_val = max(max_val, self.tree[low])\n low += 1\n \n # If high is a left child, take its max now, then get out of this\n # subtree to avoid its sibling which we do not want.\n if high & 1 == 0:\n max_val = max(max_val, self.tree[high])\n high -= 1\n\n # Progress to to the parent nodes.\n low, high = low // 2, high // 2\n return max_val\n\nclass Solution:\n def lengthOfLIS(self, nums: List[int], k: int) -> int:\n n = max(nums)\n seg = SegmentTreeMax(n)\n for num in nums:\n # Look for preceeding subsequences that ended with a value between\n # num - k and num - 1. Each value is the max length of that\n # that subsequence and we are querying the max of those values.\n low_bound = max(0, num - k)\n lis = seg.query(low_bound, num - 1)\n\n # If we find any preceeding subsequences in that range, then we can\n # do one better by adding num to the subsequence. Update the\n # segment tree to reflect that.\n seg.update(num, lis + 1)\n \n # The longest increasing subsequence is the max value in our segment\n # tree. We can get this by querying the entire range. Alternatively we\n # can return seg.tree[1] which is the root node.\n return seg.query(1, n)\n\n``` | 0 | 0 | ['Python3'] | 0 |
longest-increasing-subsequence-ii | Dynamic Programming || AVS | dynamic-programming-avs-by-vishal1431-odzk | \n# Code\ncpp []\nclass Solution {\npublic:\n int n;\n vector<int> segtree;\n \n int BestRange(int start, int end) {\n int res = 0;\n | Vishal1431 | NORMAL | 2024-10-19T12:58:45.183955+00:00 | 2024-10-19T12:58:45.183999+00:00 | 41 | false | \n# Code\n```cpp []\nclass Solution {\npublic:\n int n;\n vector<int> segtree;\n \n int BestRange(int start, int end) {\n int res = 0;\n start += 1e5 - 1;\n end += 1e5 - 1;\n \n while (start < end) {\n res = max({segtree[start], segtree[end], res});\n if (start % 2 == 0) start++;\n if (end % 2 == 1) end--;\n start = (start - 1) / 2;\n end = (end - 1) / 2;\n }\n \n if (start == end) res = max(segtree[start], res);\n \n return res;\n }\n \n void Update(int idx, int newlen) {\n idx += 1e5 - 1;\n while (idx >= 0) {\n segtree[idx] = max(newlen, segtree[idx]);\n if (idx == 0) idx = -1;\n else idx = (idx - 1) / 2;\n }\n return;\n }\n \n int lengthOfLIS(vector<int>& nums, int k) {\n int ans = 0;\n n = nums.size();\n segtree.resize(2e5);\n \n for (int i = 0; i < n; i++) nums[i]--;\n \n for (int i : nums) {\n int longest = 1;\n if (i > 0) longest = BestRange(max(i - k, 0), i - 1) + 1;\n ans = max(longest, ans);\n Update(i, longest);\n }\n \n return ans;\n }\n};\n``` | 0 | 0 | ['Dynamic Programming', 'Segment Tree', 'C++'] | 0 |
longest-increasing-subsequence-ii | Longest increasing subsequence ii | longest-increasing-subsequence-ii-by-nit-e63d | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Nityananadh | NORMAL | 2024-10-12T04:29:33.880051+00:00 | 2024-10-12T04:29:33.880086+00:00 | 19 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n\n int N = 100001;\n int[] seg = new int[2*N];\n \n void update(int pos, int val){ // update max\n pos += N;\n seg[pos] = val;\n \n while (pos > 1) {\n pos >>= 1;\n seg[pos] = Math.max(seg[2*pos], seg[2*pos+1]);\n }\n }\n \n int query(int lo, int hi){ // query max [lo, hi)\n lo += N;\n hi += N;\n int res = 0;\n \n while (lo < hi) {\n if ((lo & 1)==1) {\n res = Math.max(res, seg[lo++]);\n }\n if ((hi & 1)==1) {\n res = Math.max(res, seg[--hi]);\n }\n lo >>= 1;\n hi >>= 1;\n }\n return res;\n }\n \n public int lengthOfLIS(int[] A, int k) {\n int ans = 0;\n for (int i = 0; i < A.length; ++i){\n int l = Math.max(0, A[i]-k);\n int r = A[i];\n int res = query(l, r) + 1; // best res for the current element\n ans = Math.max(res, ans);\n update(A[i], res); // and update it here\n }\n return ans;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
longest-increasing-subsequence-ii | Go Segment Tree | go-segment-tree-by-german_gorelkin-3n3x | \n\n# Code\ngolang []\nfunc lengthOfLIS(nums []int, k int) int {\n\tst := NewSegmentTree(nums)\n\n\tfor _, n := range nums {\n\t\tn--\n\t\tl := max(0, n-k)\n\t\ | german_gorelkin | NORMAL | 2024-10-03T08:29:47.754513+00:00 | 2024-10-03T08:29:47.754534+00:00 | 2 | false | \n\n# Code\n```golang []\nfunc lengthOfLIS(nums []int, k int) int {\n\tst := NewSegmentTree(nums)\n\n\tfor _, n := range nums {\n\t\tn--\n\t\tl := max(0, n-k)\n\t\tlmax := st.query(l, n-1, 0, st.n-1, 0)\n\t\tlmax++\n\t\tst.update(n, lmax, 0, st.n-1, 0)\n\t}\n\n\treturn st.maxVal()\n}\n\nfunc maxVal(nums []int) int {\n\tres := nums[0]\n\tfor _, n := range nums {\n\t\tres = max(res, n)\n\t}\n\treturn res\n}\n\ntype SegmentTree struct {\n\ttree []int\n\tn int\n}\n\nfunc NewSegmentTree(nums []int) SegmentTree {\n\tn := maxVal(nums)\n\tsize := 2*int(math.Pow(2, math.Ceil(math.Log2(float64(n))))) - 1\n\ttree := make([]int, size)\n\tst := SegmentTree{\n\t\ttree: tree,\n\t\tn: n,\n\t}\n\n\treturn st\n}\n\nfunc (st SegmentTree) maxVal() int {\n\treturn st.tree[0]\n}\n\nfunc (st SegmentTree) update(index int, value int, start, end int, node int) {\n\tif start == end {\n\t\tst.tree[node] = value\n\t\treturn\n\t}\n\n\tmid := (start + end) / 2\n\tif index <= mid {\n\t\tst.update(index, value, start, mid, 2*node+1)\n\t} else {\n\t\tst.update(index, value, mid+1, end, 2*node+2)\n\t}\n\n\tst.tree[node] = max(st.tree[2*node+1], st.tree[2*node+2])\n}\n\nfunc (st SegmentTree) query(l, r, start, end, node int) int {\n\tif l > end || r < start {\n\t\treturn 0\n\t}\n\tif l <= start && r >= end {\n\t\treturn st.tree[node]\n\t}\n\n\tmid := (start + end) / 2\n\tleftMax := st.query(l, r, start, mid, 2*node+1)\n\trightMax := st.query(l, r, mid+1, end, 2*node+2)\n\treturn max(leftMax, rightMax)\n}\n``` | 0 | 0 | ['Segment Tree', 'Go'] | 0 |
longest-increasing-subsequence-ii | DP w/ Segment Tree | dp-w-segment-tree-by-anastasiskolio13-wz13 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | anastasiskolio13 | NORMAL | 2024-09-30T04:08:56.214907+00:00 | 2024-09-30T04:10:35.724729+00:00 | 26 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n$$\\mathcal{O}(N \\cdot \\text{log } (\\max_{0 \\leq i \\leq N - 1}\\{A[i]\\} + K))$$\n\n- Space complexity:\n$$\\mathcal{O}(N + \\max_{0 \\leq i \\leq N - 1}\\{A[i]\\} + K)$$\n\n# Code\n```cpp []\nclass Solution {\npublic:\n vector<int> T, dp;\n\n int Query(int lo, int hi, int v, int qlo, int qhi) {\n if (qlo <= lo && hi <= qhi)\n return T[v];\n if (qlo > hi || qhi < lo)\n return 0;\n int mid = (lo + hi) / 2;\n int x = Query(lo, mid, 2 * v, qlo, qhi);\n int y = Query(mid + 1, hi, 2 * v + 1, qlo, qhi);\n return max(x, y);\n }\n\n void Update(int lo, int hi, int v, int i, int x) {\n if (lo == hi) {\n T[v] = x;\n return;\n }\n int mid = (lo + hi) / 2;\n if (i <= mid)\n Update(lo, mid, 2 * v, i, x);\n else \n Update(mid + 1, hi, 2 * v + 1, i, x);\n T[v] = max(T[2 * v], T[2 * v + 1]);\n }\n\n int lengthOfLIS(vector<int>& A, int K) {\n int N = A.size(), maxValue = *max_element(A.begin(), A.end()); \n dp.resize(N); T.resize(4 * (maxValue + K) + 1);\n for (int i = N - 1; i >= 0; i--) {\n dp[i] = Query(1, maxValue + K, 1, A[i] + 1, A[i] + K) + 1;\n Update(1, maxValue + K, 1, A[i], dp[i]);\n }\n return *max_element(dp.begin(), dp.begin() + N);\n }\n};\n``` | 0 | 0 | ['Dynamic Programming', 'Segment Tree', 'C++'] | 0 |
longest-increasing-subsequence-ii | longest-increasing-subsequence-ii - Java Solution | longest-increasing-subsequence-ii-java-s-blid | \n# Code\njava []\nclass Solution {\n class Node{\n int val;\n Node left;\n Node right;\n int start;\n int end;\n }\n | himashusharma | NORMAL | 2024-09-25T07:40:27.426633+00:00 | 2024-09-25T07:40:27.426677+00:00 | 18 | false | \n# Code\n```java []\nclass Solution {\n class Node{\n int val;\n Node left;\n Node right;\n int start;\n int end;\n }\n public int lengthOfLIS(int[] nums, int k) {\n int max = 0;\n for(int num : nums){\n max = Math.max(max,num);\n }\n \n Node root = construct(1,max);\n \n int res = 0;\n for(int num : nums){\n int lo = (num - k) < 1 ? 1 : (num - k);\n int hi = num - 1;\n \n int len = query(root,lo,hi) + 1;\n \n update(root,num,len);\n res = Math.max(res,len);\n } \n return res;\n }\n \n Node construct(int ss,int se){\n if(ss == se){\n Node node = new Node();\n node.start = ss;\n node.end = se;\n node.val = 0;\n return node;\n }\n \n int mid = (ss + se) / 2;\n Node node = new Node();\n node.start = ss;\n node.end = se;\n node.left = construct(ss,mid);\n node.right = construct(mid+1,se);\n node.val = Math.max(node.left.val,node.right.val);\n \n return node;\n }\n \n void update(Node node,int idx,int val){\n if(node.start == node.end){\n node.val = val;\n return;\n }\n \n int mid = (node.start + node.end) / 2;\n if(idx <= mid){\n update(node.left,idx,val);\n }else{\n update(node.right,idx,val);\n }\n \n node.val = Math.max(node.left.val,node.right.val);\n }\n \n int query(Node node,int qs,int qe){\n if(node.start > qe || node.end < qs){\n return 0;\n }else if(node.start >= qs && node.end <= qe){\n return node.val;\n }else{\n int lval = query(node.left,qs,qe);\n int rval = query(node.right,qs,qe);\n return Math.max(lval,rval);\n }\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
longest-increasing-subsequence-ii | Golang segment tree | golang-segment-tree-by-alishagupta262-swga | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | alishagupta262 | NORMAL | 2024-09-07T10:08:21.418920+00:00 | 2024-09-07T10:08:21.418951+00:00 | 3 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```golang []\nfunc lengthOfLIS(nums []int, k int) int {\n\tmx := slices.Max(nums)\n\ttree := newSegmentTree(mx)\n\tans := 1\n\tfor _, v := range nums {\n\t\tt := tree.query(1, v-k, v-1) + 1\n\t\tans = max(ans, t)\n\t\ttree.modify(1, v, t)\n\t}\n\treturn ans\n}\n\ntype node struct {\n\tl int\n\tr int\n\tv int\n}\n\ntype segmentTree struct {\n\ttr []*node\n}\n\nfunc newSegmentTree(n int) *segmentTree {\n\ttr := make([]*node, n<<2)\n\tfor i := range tr {\n\t\ttr[i] = &node{}\n\t}\n\tt := &segmentTree{tr}\n\tt.build(1, 1, n)\n\treturn t\n}\n\nfunc (t *segmentTree) build(u, l, r int) {\n\tt.tr[u].l, t.tr[u].r = l, r\n\tif l == r {\n\t\treturn\n\t}\n\tmid := (l + r) >> 1\n\tt.build(u<<1, l, mid)\n\tt.build(u<<1|1, mid+1, r)\n\tt.pushup(u)\n}\n\nfunc (t *segmentTree) modify(u, x, v int) {\n\tif t.tr[u].l == x && t.tr[u].r == x {\n\t\tt.tr[u].v = v\n\t\treturn\n\t}\n\tmid := (t.tr[u].l + t.tr[u].r) >> 1\n\tif x <= mid {\n\t\tt.modify(u<<1, x, v)\n\t} else {\n\t\tt.modify(u<<1|1, x, v)\n\t}\n\tt.pushup(u)\n}\n\nfunc (t *segmentTree) query(u, l, r int) int {\n\tif t.tr[u].l >= l && t.tr[u].r <= r {\n\t\treturn t.tr[u].v\n\t}\n\tmid := (t.tr[u].l + t.tr[u].r) >> 1\n\tv := 0\n\tif l <= mid {\n\t\tv = t.query(u<<1, l, r)\n\t}\n\tif r > mid {\n\t\tv = max(v, t.query(u<<1|1, l, r))\n\t}\n\treturn v\n}\n\nfunc (t *segmentTree) pushup(u int) {\n\tt.tr[u].v = max(t.tr[u<<1].v, t.tr[u<<1|1].v)\n}\n``` | 0 | 0 | ['Go'] | 0 |
longest-increasing-subsequence-ii | 3 liner Logic for a Segment Tree Solution || Explained | 3-liner-logic-for-a-segment-tree-solutio-iaey | Complexity\n- Time complexity: O(n*log(n)) \n\n- Space complexity: O(n) \n\n# Code\ncpp []\nclass SegmentTree\n{\n int len;\n vector<int> seg;\n\n void comb | coder_rastogi_21 | NORMAL | 2024-08-30T19:00:36.308398+00:00 | 2024-08-30T19:00:36.308422+00:00 | 15 | false | # Complexity\n- Time complexity: $$O(n*log(n))$$ \n\n- Space complexity: $$O(n)$$ \n\n# Code\n```cpp []\nclass SegmentTree\n{\n int len;\n vector<int> seg;\n\n void combine(int ind) { \n\t\t seg[ind] = max(seg[2*ind+1],seg[2*ind+2]); \n\t }\n\n int query(int ind, int low, int high, int l, int r)\n {\n if(low > r || high < l)\n return 0;\n \n if(l <= low && high <= r)\n return seg[ind];\n \n int mid = (low + high)/2;\n int left = query(2*ind+1,low,mid,l,r);\n int right = query(2*ind+2,mid+1,high,l,r);\n return max(left,right);\n }\n\n void update(int ind, int low, int high, int index, int val)\n {\n if(low == high) {\n seg[ind] = val;\n return;\n }\n int mid = (low + high)/2;\n if(index <= mid)\n update(2*ind+1,low,mid,index,val);\n else\n update(2*ind+2,mid+1,high,index,val);\n combine(ind);\n }\n\n public:\n SegmentTree(int n) {\n len = n;\n seg.resize(4*len+1);\n }\n\n void update(int index, int val) {\n update(0,0,len-1,index,val);\n }\n\n int query(int l, int r) {\n return query(0,0,len-1,l,r);\n }\n};\n\nclass Solution {\npublic:\n int lengthOfLIS(vector<int>& nums, int k) {\n int ans = 1;\n SegmentTree st(1e5+5);\n\n for(auto it : nums) {\n // we want numbers in the range it-k and it-1 \n // and can place \'it\' after maximum value among them\n int maxTillNow = st.query(it-k, it-1);\n ans = max(ans, 1 + maxTillNow);\n st.update(it, 1 + maxTillNow); // update answer for current value\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Segment Tree', 'C++'] | 0 |
longest-increasing-subsequence-ii | 2407. Longest Increasing Subsequence II | 2407-longest-increasing-subsequence-ii-b-za0o | Intuition\n Describe your first thoughts on how to solve this problem. \nUse segment Trees to find max(dp[j]) such that j < nums[i] && j <= nums[i] - k \n\n# Ap | avneeshpathak93 | NORMAL | 2024-08-19T05:52:16.095691+00:00 | 2024-08-19T05:52:16.095739+00:00 | 46 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse segment Trees to find max(dp[j]) such that j < nums[i] && j <= nums[i] - k \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can optimize query using segment Trees.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(nlog(maxi))\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(maxi)\n\n# Code\n```\nclass Solution {\n int query(int node, int start, int end, int l, int r, vector<int> &segment_tree){\n if(end < l || r < start) return INT_MIN;\n if(l <= start && end <= r) return segment_tree[node];\n int mid = (start + end) / 2;\n int left = query(node * 2 + 1, start, mid, l, r, segment_tree);\n int right = query(node * 2 + 2, mid + 1, end, l, r, segment_tree);\n return max(left, right);\n }\n\n void update(int node, int start, int end, int idx, int val, vector<int> &segment_tree){\n if(start == end) {\n segment_tree[node] = max(segment_tree[node], val);\n return;\n }\n int mid = (start + end) / 2;\n if(idx <= mid) update(node * 2 + 1, start, mid, idx, val, segment_tree);\n else update(node * 2 + 2, mid + 1, end, idx, val, segment_tree);\n\n segment_tree[node] = max(segment_tree[node * 2 + 1], segment_tree[node * 2 + 2]);\n return; \n }\npublic:\n int lengthOfLIS(vector<int>& nums, int k) {\n int n = nums.size(), maxi = INT_MIN;\n for(int i = 0; i < n; i++) maxi = max(maxi, nums[i]);\n vector<int> segment_tree(4 * maxi, 0);\n int ans = 0;\n for(int i = 0; i < n; i++){\n int temp = 1 + query(0, 0, maxi, nums[i] - k, nums[i] - 1, segment_tree);\n update(0, 0, maxi, nums[i], temp, segment_tree);\n ans = max(ans, temp);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
longest-increasing-subsequence-ii | Longest Increasing Subsequence 2 | longest-increasing-subsequence-2-by-tome-c3x2 | Intuition\n Describe your first thoughts on how to solve this problem. \nSegment Tree\n# Approach\n Describe your approach to solving the problem. \nSegment Tre | tomerdrr | NORMAL | 2024-07-21T09:55:27.660573+00:00 | 2024-07-21T09:55:27.660618+00:00 | 4 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSegment Tree\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSegment Tree\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n*k)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\nclass SEG:\n def __init__(self, n):\n self.n = n\n self.tree = [0] * 2 * self.n\n \n def query(self, l, r):\n l += self.n\n r += self.n\n ans = 0\n while l < r:\n if l & 1:\n ans = max(ans, self.tree[l])\n l += 1\n if r & 1:\n r -= 1\n ans = max(ans, self.tree[r])\n l >>= 1\n r >>= 1\n return ans\n \n def update(self, i, val):\n i += self.n\n self.tree[i] = val\n while i > 1:\n i >>= 1\n self.tree[i] = max(self.tree[i * 2], self.tree[i * 2 + 1])\n\nclass Solution(object):\n def lengthOfLIS(self, nums, k):\n """\n :type nums: List[int]\n :type k: int\n :rtype: int\n """\n n, ans = max(nums), 1\n seg = SEG(n)\n for a in nums:\n a -= 1\n premax = seg.query(max(0, a - k), a)\n ans = max(ans, premax + 1)\n seg.update(a, premax + 1)\n return ans\n``` | 0 | 0 | ['Python'] | 0 |
longest-increasing-subsequence-ii | Python (Simple Segment Tree) | python-simple-segment-tree-by-rnotappl-lyxp | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | rnotappl | NORMAL | 2024-07-20T09:55:57.225569+00:00 | 2024-07-20T09:55:57.225596+00:00 | 3 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def lengthOfLIS(self, nums, k):\n n = max(nums) + 1\n\n ans = [0]*(2*n) \n\n def update(idx,val):\n idx += n\n ans[idx] = val\n\n while idx > 1:\n idx = idx//2\n ans[idx] = max(ans[2*idx],ans[2*idx+1])\n \n def getMax(left, right):\n left += n \n right += n\n max_val = ans[left]\n\n while left < right:\n if left&1:\n max_val = max(max_val,ans[left])\n left += 1 \n if right&1:\n right -= 1 \n max_val = max(max_val,ans[right])\n left = left//2\n right = right//2\n \n return max_val\n\n for num in nums:\n prev_longest_sub = getMax(max(num-k,0),num)\n update(num,prev_longest_sub+1)\n\n return ans[1]\n``` | 0 | 0 | ['Python3'] | 0 |
longest-increasing-subsequence-ii | Python (Simple DP) | python-simple-dp-by-rnotappl-7nad | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | rnotappl | NORMAL | 2024-07-19T16:56:39.556748+00:00 | 2024-07-19T16:56:39.556777+00:00 | 32 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def lengthOfLIS(self, nums, k):\n n = max(nums) + 1\n\n ans = [0]*(2*n)\n\n def update(idx, value):\n idx += n\n ans[idx] = value \n\n while idx > 1:\n idx = idx>>1 \n ans[idx] = max(ans[idx<<1],ans[idx<<1|1])\n \n def getMax(left, right):\n left += n \n right += n\n max_val = ans[left]\n\n while left < right:\n if left&1:\n max_val = max(max_val,ans[left])\n left += 1 \n if right&1:\n right -= 1 \n max_val = max(max_val,ans[right])\n left = left>>1 \n right = right>>1\n \n return max_val\n\n for num in nums:\n prev_longest_sub = getMax(max(num-k,0),num)\n update(num, prev_longest_sub+1)\n\n return ans[1]\n``` | 0 | 0 | ['Python3'] | 0 |
longest-increasing-subsequence-ii | Not a fully passed solution, but the code is short. 80/84 passed. Any good idea to pass it? | not-a-fully-passed-solution-but-the-code-3zv1 | Intuition\nI am using the TreeMap (Segment Tree), array item value as key, the length of the longest subsequence ending with it as the value.\n\n\n# Approach\n\ | qiuping345 | NORMAL | 2024-07-11T07:01:35.281576+00:00 | 2024-07-11T07:01:35.281599+00:00 | 17 | false | # Intuition\nI am using the TreeMap (Segment Tree), array item value as key, the length of the longest subsequence ending with it as the value.\n\n\n# Approach\n\n\n# Complexity\n- Time complexity:\nTypically O(n*lg(n)), worst case O(n^2)\n\nI passed 80 test cases out of the 84. Failed on the worst cases, that are increasing and K is very big. Any suggestion to pass it base on this short code is appreciated. \n\n# Code\n```\nclass Solution {\n public int lengthOfLIS(int[] nums, int k) {\n int max = 0;\n TreeMap<Integer, Integer> map = new TreeMap();\n for(int i = 0; i < nums.length; i++) {\n int len = 1;\n if(!map.isEmpty()) {\n Integer lowerKey = map.lowerKey(nums[i]);\n while(lowerKey != null && nums[i] - lowerKey <= k) {\n len = Math.max(len, map.get(lowerKey) + 1);\n lowerKey = map.lowerKey(lowerKey);\n }\n }\n max = Math.max(max, len);\n map.put(nums[i], Math.max(len, map.getOrDefault(nums[i], 0)));\n }\n return max;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
longest-increasing-subsequence-ii | My take on this Problem | my-take-on-this-problem-by-amit130-8ode | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Amit130 | NORMAL | 2024-07-11T06:16:13.205750+00:00 | 2024-07-11T06:16:13.205788+00:00 | 124 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n log n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass SegmentTree{\n public:\n int leftIndex;\n int rightIndex;\n SegmentTree* left;\n SegmentTree* right;\n int maxNum;\n SegmentTree(int leftI,int rightI,int val){\n leftIndex=leftI;\n rightIndex=rightI;\n maxNum=val;\n left=NULL;\n right=NULL;\n } \n\n void updateTree(int index,int val,SegmentTree* root){\n if(root->leftIndex==root->rightIndex){\n root->maxNum=val;\n return;\n }\n\n int midIndex=(root->leftIndex+root->rightIndex)/2;\n if(midIndex>=index){\n updateTree(index,val,root->left);\n } else {\n updateTree(index,val,root->right);\n }\n root->maxNum=max(root->left->maxNum,root->right->maxNum);\n return;\n }\n\n \n int query(int leftI,int rightI,SegmentTree* root){\n if(root->rightIndex==rightI && root->leftIndex==leftI)\n return root->maxNum;\n\n if(leftI>rightI){\n return -1;\n }\n\n int midIndex=(root->leftIndex+root->rightIndex)/2;\n int ans=0;\n if(leftI<=midIndex && midIndex<=rightI){\n ans=max(ans,max(query(leftI,midIndex,root->left),query(midIndex+1,rightI,root->right)));\n } else if(midIndex<leftI) {\n ans=max(ans,query(leftI,rightI,root->right));\n } else {\n ans=max(ans,query(leftI,rightI,root->left));\n }\n return ans;\n }\n};\n\nSegmentTree* construct(int leftI,int rightI){\n if(leftI==rightI){\n return new SegmentTree(leftI,rightI,-1);\n }\n\n int midIndex=(leftI+rightI)/2;\n SegmentTree* root=new SegmentTree(leftI,rightI,0);\n SegmentTree* leftTree=construct(leftI,midIndex);\n SegmentTree* rightTree=construct(midIndex+1,rightI);\n root->left=leftTree;\n root->right=rightTree;\n root->maxNum=max(leftTree->maxNum,rightTree->maxNum);\n return root;\n}\n\nclass Solution {\npublic:\n int lengthOfLIS(vector<int>& nums, int k) {\n int maxN=-1;\n for(auto n:nums){\n maxN=max(maxN,n);\n }\n stack<int> st;\n SegmentTree* root;\n root=construct(0,maxN+k);\n int ans=1;\n for(int i=nums.size()-1;i>=0;i--){\n int n=nums[i];\n while(!st.empty() && (st.top()<=n || st.top()>n+k)){\n st.pop();\n }\n st.push(n);\n int l=root->query(n+1,n+k,root)+1;\n ans=max(ans,l);\n root->updateTree(n,l,root);\n } \n return ans; \n }\n};\n``` | 0 | 0 | ['Array', 'Divide and Conquer', 'Dynamic Programming', 'Binary Indexed Tree', 'Segment Tree', 'Monotonic Stack', 'C++'] | 0 |
longest-increasing-subsequence-ii | My take on this Problem | my-take-on-this-problem-by-amit130-ked9 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Amit130 | NORMAL | 2024-07-11T06:16:04.564009+00:00 | 2024-07-11T06:16:04.564036+00:00 | 13 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n log n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass SegmentTree{\n public:\n int leftIndex;\n int rightIndex;\n SegmentTree* left;\n SegmentTree* right;\n int maxNum;\n SegmentTree(int leftI,int rightI,int val){\n leftIndex=leftI;\n rightIndex=rightI;\n maxNum=val;\n left=NULL;\n right=NULL;\n } \n\n void updateTree(int index,int val,SegmentTree* root){\n if(root->leftIndex==root->rightIndex){\n root->maxNum=val;\n return;\n }\n\n int midIndex=(root->leftIndex+root->rightIndex)/2;\n if(midIndex>=index){\n updateTree(index,val,root->left);\n } else {\n updateTree(index,val,root->right);\n }\n root->maxNum=max(root->left->maxNum,root->right->maxNum);\n return;\n }\n\n \n int query(int leftI,int rightI,SegmentTree* root){\n if(root->rightIndex==rightI && root->leftIndex==leftI)\n return root->maxNum;\n\n if(leftI>rightI){\n return -1;\n }\n\n int midIndex=(root->leftIndex+root->rightIndex)/2;\n int ans=0;\n if(leftI<=midIndex && midIndex<=rightI){\n ans=max(ans,max(query(leftI,midIndex,root->left),query(midIndex+1,rightI,root->right)));\n } else if(midIndex<leftI) {\n ans=max(ans,query(leftI,rightI,root->right));\n } else {\n ans=max(ans,query(leftI,rightI,root->left));\n }\n return ans;\n }\n};\n\nSegmentTree* construct(int leftI,int rightI,vector<int>& nums){\n if(leftI==rightI){\n return new SegmentTree(leftI,rightI,nums[leftI]);\n }\n\n int midIndex=(leftI+rightI)/2;\n SegmentTree* root=new SegmentTree(leftI,rightI,0);\n SegmentTree* leftTree=construct(leftI,midIndex,nums);\n SegmentTree* rightTree=construct(midIndex+1,rightI,nums);\n root->left=leftTree;\n root->right=rightTree;\n root->maxNum=max(leftTree->maxNum,rightTree->maxNum);\n return root;\n}\n\nclass Solution {\npublic:\n int lengthOfLIS(vector<int>& nums, int k) {\n int maxN=-1;\n for(auto n:nums){\n maxN=max(maxN,n);\n }\n stack<int> st;\n SegmentTree* root;\n vector<int> vec(maxN+k+1,-1); \n root=construct(0,vec.size()-1,vec);\n int ans=1;\n for(int i=nums.size()-1;i>=0;i--){\n int n=nums[i];\n while(!st.empty() && (st.top()<=n || st.top()>n+k)){\n st.pop();\n }\n st.push(n);\n int l=root->query(n+1,n+k,root)+1;\n ans=max(ans,l);\n root->updateTree(n,l,root);\n } \n return ans; \n }\n};\n``` | 0 | 0 | ['Segment Tree', 'Monotonic Stack'] | 0 |
longest-increasing-subsequence-ii | [Segment Tree] Intuition + Explanation | segment-tree-intuition-explanation-by-an-bjoa | Intuition\nSegment Tree would help noting the longest known subsequence for any last number between [l, r]\n\n# Approach\n- For each i, query the longest known | anushree97 | NORMAL | 2024-07-08T17:14:52.001983+00:00 | 2024-07-08T17:14:52.002016+00:00 | 20 | false | # Intuition\nSegment Tree would help noting the longest known subsequence for any last number between [l, r]\n\n# Approach\n- For each i, query the longest known subsequence whose last number is between range [max(i-k), i-1]\n- Now add 1 to above query and update it in vertex of (i)\n- Each vertex would store longest subsequence with last number in range [tl, tr]\n\n# Complexity\n- Time complexity:\nQuery - O(logn)\nUpdate - O(logn)\nFor each i - O(2logn)\nWe have to query n times - O(2nlogn) = O(nlogn)\n\n- Space complexity:\nO(logn)\n\n# Code\n```\nclass SegmentTree:\n def __init__(self):\n self.t = [0]*(4*(10**5))\n\n def query(self, l, r):\n return self._query(1, 0, 10**5, l, r)\n\n def _query(self, v, tl, tr, l, r):\n if l>tr or r<tl: return 0\n if tr==tl:\n return self.t[v]\n if l<=tl and tr<=r:\n return self.t[v]\n tm = (tl+tr)//2\n return max(self._query(2*v, tl, tm, l, r), self._query(2*v+1, tm+1, tr, l, r))\n\n def update(self, pos, val):\n self._update(1, 0, 10**5, pos, val)\n\n def _update(self, v, tl, tr, pos, val):\n if tl==tr==pos:\n self.t[v]=val\n return\n tm = (tl+tr)//2\n if pos<=tm:\n self._update(2*v, tl, tm, pos, val)\n else:\n self._update(2*v+1, tm+1, tr, pos, val)\n\n self.t[v] = max(self.t[2*v], self.t[2*v+1])\n\nclass Solution:\n def lengthOfLIS(self, nums: List[int], k: int) -> int:\n sg = SegmentTree()\n\n for i in nums:\n r = sg.query(max(i-k, 0), i-1)\n sg.update(i, r+1)\n\n return sg.query(0, 10**5)\n``` | 0 | 0 | ['Segment Tree', 'Python3'] | 0 |
longest-increasing-subsequence-ii | ap | ap-by-ap5123-uvbv | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | ap5123 | NORMAL | 2024-07-06T13:14:57.360446+00:00 | 2024-07-06T13:14:57.360483+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\nvoid build(int ind,int i,int j,vector<int>&seg,vector<int>&arr)\n{\n if(i==j)\n {\n seg[ind]=arr[i];\n return;\n }\n\n int mid=i+(j-i)/2;\n build(2*ind+1,i,mid,seg,arr);\n build(2*ind+2,mid+1,j,seg,arr);\n seg[ind]=max(seg[2*ind+1],seg[2*ind+2]);\n}\nint query(int ind,int low,int high,vector<int>&seg,int l,int r)\n{\n if(l>high||r<low)return -1e9;\n if(l<=low&&r>=high)return seg[ind];\n\n int mid=(low+high)/2;\n int left=query(2*ind+1,low,mid,seg,l,r);\n int right=query(2*ind+2,mid+1,high,seg,l,r);\n\n return max(left,right);\n}\nvoid update(int ind,int low,int high,int i,int val,vector<int>&seg)\n{\n if(low==high)\n {\n seg[ind]=max(seg[ind],val);\n return;\n }\n int mid=(low+high)/2;\n if(i<=mid)\n {\n update(2*ind+1,low,mid,i,val,seg);\n }else\n {\n update(2*ind+2,mid+1,high,i,val,seg);\n }\n\n seg[ind]=max(seg[2*ind+1],seg[2*ind+2]);\n}\n int lengthOfLIS(vector<int>& nums, int k) {\n int n=nums.size();\n if(n==1)return 1;\n int maxi=0;\n int ans=0;\n for(auto i:nums)maxi=max(maxi,i);\n vector<int> arr(maxi+1,0);\n vector<int> seg(4*maxi+1);\n build(0,0,maxi,seg,arr);\n update(0,0,maxi,nums[n-1],1,seg);\n for(int i=n-2;i>=0;i--)\n {\n if(nums[i]==maxi)\n {\n update(0,0,maxi,nums[i],1,seg);\n continue;\n }\n\n int l=nums[i]+1;\n int r=min(maxi,nums[i]+k);\n int temp=query(0,0,maxi,seg,l,r);\n if(temp==-1e9)\n {\n temp=0;\n }\n update(0,0,maxi,nums[i],temp+1,seg);\n }\n ans=query(0,0,maxi,seg,0,maxi);\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
longest-increasing-subsequence-ii | Solution | solution-by-penrosecat-9nhd | Intuition\n Describe your first thoughts on how to solve this problem. \nThe underlying array of the segment tree represents the length of LIS ending with nums[ | penrosecat | NORMAL | 2024-07-05T07:16:33.202693+00:00 | 2024-07-05T07:16:33.202713+00:00 | 3 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe underlying array of the segment tree represents the length of LIS ending with nums[i] in the array from 1 to max(nums[i]).\n\nNow, for an element nums[i], we have to get (range query) the max length of LIS from nums[i]-k to nums[i]-1 in the segment tree and then point update the value at index nums[i].\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass SegTree{\n public:\n int n;\n vector<int> arr;\n vector<int> t;\n\n SegTree(int n)\n {\n this->n = n;\n t.assign(2*n, 0);\n arr.assign(n, 0);\n }\n\n void update(int i, int l, int r, int pos, int val)\n {\n if(l > pos || r < pos || l > r)\n {\n return;\n }\n\n if(l == r)\n {\n arr[pos] = val;\n t[i] = val;\n return;\n }\n\n int mid = l + (r-l)/2;\n update(i+1, l, mid, pos, val);\n update(i + 2*(mid - l + 1), mid+1, r, pos, val);\n t[i] = max(t[i+1], t[i + 2*(mid - l + 1)]);\n }\n\n int query(int i, int l, int r, int lq, int rq)\n {\n if(lq > rq || l > rq || r < lq)\n {\n return 0;\n }\n\n if(lq <= l && r <= rq)\n {\n return t[i];\n }\n\n int mid = l + (r-l)/2;\n return max(query(i+1, l, mid, lq, rq),\n query(i+2*(mid - l + 1), mid+1, r, lq, rq));\n\n }\n}; \n\nclass Solution {\npublic:\n\n int lengthOfLIS(vector<int>& nums, int k) {\n int n = *max_element(nums.begin(), nums.end());\n SegTree st(n);\n\n for(int i = 0; i<nums.size(); i++)\n {\n int maxlenbefore = st.query(0, 0, n-1, max(nums[i]-k-1,0), nums[i]-1-1);\n st.update(0, 0, n-1, nums[i]-1, maxlenbefore + 1);\n }\n\n return st.t[0];\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
longest-increasing-subsequence-ii | LIS + Segment tree | lis-segment-tree-by-laithy_uchiha-lni5 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Laithy_uchiha | NORMAL | 2024-07-02T16:00:14.520985+00:00 | 2024-07-02T16:00:14.521084+00:00 | 33 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nconst int N=1e5+2;\nclass Solution {\npublic:\n\n int seg[4*N];\n void build(int node,int s,int e){\n if(s==e){\n seg[node]=0;\n return;\n }\n int mid=(s+e)/2;\n build(2*node+1,s,mid);\n build(2*node+2,mid+1,e);\n seg[node]=max(seg[2*node+1] , seg[2*node+2]);\n}\n\n void update(int node,int s,int e,int idx,int val){\n if(s==e){\n seg[node]=val;\n return;\n }\n int mid=(s+e)/2;\n if(idx>=s && idx<=mid){\n update(2*node+1,s,mid,idx,val);\n }\n else{\n update(2*node+2,mid+1,e,idx,val);\n }\n seg[node]=max(seg[2*node+1] , seg[2*node+2]);\n }\n\n int query(int node,int s,int e,int l,int r){\n if(s>r || e<l) return 0;\n if(s>=l && e<=r) return seg[node];\n int mid=(s+e)/2;\n return max(query(2*node+1,s,mid,l,r) , query(2*node+2,mid+1,e,l,r));\n }\n\n int lengthOfLIS(vector<int>& arr, int k) {\n int n=arr.size();\n vector<pair<int,int>>pr(n);\n for(int i=0;i<n;i++){\n pr[i]={arr[i],i};\n }\n sort(pr.begin(),pr.end());\n build(0,0,n-1);\n map<pair<int,int>,int>mp;\n for(int i=0;i<n;i++){\n mp[pr[i]]=i;\n }\n int ans=1;\n for(int i=0;i<n;i++){\n int up_bound=lower_bound(pr.begin(),pr.end(),make_pair(arr[i],-1))-pr.begin();\n int low_bound=lower_bound(pr.begin(),pr.end(),make_pair(arr[i]-k,-1))-pr.begin();\n int x=1+query(0,0,n-1,low_bound,up_bound-1);\n ans=max(ans,x);\n update(0,0,n-1,mp[{arr[i],i}],x);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
string-transformation | 【C++ || Java || Python】 Short Code by Finding the Pattern | c-java-python-short-code-by-finding-the-px422 | I know almost nothing about English, pointing out the mistakes in my article would be much appreciated.\n\n> In addition, I\'m too weak, please be critical of m | RealFan | NORMAL | 2023-09-10T04:05:18.991287+00:00 | 2024-01-14T03:57:12.972032+00:00 | 8,017 | false | > **I know almost nothing about English, pointing out the mistakes in my article would be much appreciated.**\n\n> **In addition, I\'m too weak, please be critical of my ideas.**\n---\n\n# Brief Solution\n**Rolling will change the beginning index of $$s$$. So enumerate each index as the beginning index, count the number of ways to obtain it. And then use [KMP](https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm) algorithm to find which indexes can let $$s=t$$, summing their counting.**\n\n# Intuition\n1. Move suffix to prefix is actually a "rolling" operation. \n Let $$s\'$$ be the string obtained after $$k$$ time rollings of string $$s$$. According to the beginning index of $$s\'$$ on $$s$$, it has at most $$n$$ kinds of situations.\n This is illustration, $$s="abcd"$$:\n \n2. Define $$f_{k}(i)$$ as "after $$k$$ steps, the number of ways which can let $$s\'$$ starting from $$s[i]$$".\n3. Because $$s$$ can be rolled with the length from $$1$$ to $$n-1$$ once, easily write a recursion function:\n $$f_{k}(i) = \\sum\\limits_{j=1}^{n-1}f_{k-1}((i-j)\\%n) = \\sum\\limits_{j=0}^{n-1}f_{k-1}(j) - f_{k-1}(i)$$\n4. Now we can try to calculate some values of $$f_{k}$$, suppose now $$n=4$$:\n$\n\\begin{array}{|c|c|c|c|c|c|} \n\\hline\n\\color{red}{k} & \\color{green}{i=0} & \\color{green}{i=1} & \\color{green}{i=2} & \\color{green}{i=3} & \\color{green}{SUM} \\\\\n\\hline\n\\color{orange}{0} & \\color{magenta}{1} & \\color{magenta}{0} & \\color{magenta}{0} & \\color{magenta}{0} & \\color{magenta}{\\textbf{1}} \\\\\n\\hline\n\\color{orange}{1} & \\color{magenta}{0} & \\color{magenta}{1} & \\color{magenta}{1} & \\color{magenta}{1} & \\color{magenta}{\\textbf{3}}\\\\\n\\hline\n\\color{orange}{2} & \\color{magenta}{3} & \\color{magenta}{2} & \\color{magenta}{2} & \\color{magenta}{2} & \\color{magenta}{\\textbf{9}}\\\\\n\\hline\n\\color{orange}{3} & \\color{magenta}{6} & \\color{magenta}{7} & \\color{magenta}{7} & \\color{magenta}{7} & \\color{magenta}{\\textbf{27}}\\\\\n\\hline\n\\color{orange}{4} & \\color{magenta}{21} & \\color{magenta}{20} & \\color{magenta}{20} & \\color{magenta}{20} & \\color{magenta}{\\textbf{81}}\\\\\n\\hline\n\\end{array}\n$\n5. From the table, what can you find?\n - $$\\sum f_{k}(i) = (n-1)^k$$\n - For all $$i \u2260 0$$, $$f_k(i)$$ equals.\n - $$f_k(0) - f_k(\\neg 0) = (-1)^{k}$$\n6. **So you can directly calculate all $$f_k(i)$$ as:\n $$f_k(1) = f_k(2)=\u2026=f_k(n-1)=\\frac{(n-1)^k-(-1)^k}{n}$$\n $$f_k(0) = f_k(1) + (-1)^k$$**\n *Explain:\n Because there are totally $$n$$ elements, and their sum is $$(n-1)^k$$. That is:\n $$f_k(0) + f_k(1) +... +f_k(n-1) = (n-1)^k$$\n And from part 5, we can transform it into:\n $$(n-1)^k=f_k(0) + (n-1) \\cdot f_k(\\neg 0)=n \\cdot f_k(\\neg 0) + (-1)^k$$\n So: $$f_k(\\neg 0) = \\frac{(n-1)^k-(-1)^k}{n}$$*\n\n7. Now we only have one problem, how to find the beginning positions which can let $$s=t$$?\n It\'s a classical problem, we can let $$ss=s+s$$, then match $$t$$ with $$ss$$ by KMP algorithm, and don\'t forget to remove the situation of $$i=n$$.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. To calculate the $$x^y$$, you need to study [fast power](https://en.wikipedia.org/wiki/Exponentiation_by_squaring) algorithm at first.\n2. For division with remainder $$\\frac{x}{y} \\% M$$, if module $$M$$ is a prime number, you can use multiply $$x \\cdot y^{M-2}$$ to calculate division.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n + \\log k)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` C++ []\nstruct StringAlgorithm {\n static std::vector<int> kmp(const std::string& s, const std::string& t) {\n int m = s.size(), n = t.size();\n std::vector<int> pi(n, 0), res;\n for (int i = 1; i < n; ++i) {\n int j = pi[i - 1];\n while (j > 0 && t[j] != t[i]) j = pi[j - 1];\n if (j == 0 && t[0] != t[i]) pi[i] = 0;\n else pi[i] = j + 1;\n }\n int j = 0;\n for (int i = 0; i < m; ++i) {\n while (j >= n || (j > 0 && s[i] != t[j])) j = pi[j - 1];\n if (s[i] == t[j]) j++;\n if (j == n) res.push_back(i - n + 1);\n }\n return res;\n } \n};\nclass Solution {\npublic:\n long long pow(long long a, long long b, const long long M) {\n if (b == 0) return 1;\n if ((b & 1) == 0) return pow(a * a % M, b >> 1, M);\n return a * pow(a * a % M, b >> 1, M) % M;\n }\n int numberOfWays(string s, string t, long long k) {\n long long n = s.size(), M = 1e9 + 7;\n auto pos = StringAlgorithm::kmp(s + s.substr(0, n-1), t);\n long long f_k[2];\n f_k[1] = (pow(n-1, k, M) + (k % 2 * 2 - 1) + M) % M * pow(n, M-2, M) % M;\n f_k[0] = (f_k[1] - (k % 2 * 2 - 1) + M) % M;\n return accumulate(pos.begin(), pos.end(), 0ll, \n [&](long long s, long long p) { return (s + f_k[!!p]) % M; } );\n }\n};\n```\n``` Java []\nclass StringAlgorithm {\n public List<Integer> kmp(String s, String t) {\n int m = s.length(), n = t.length();\n int []pi = new int[n];\n for (int i = 1; i < n; ++i) {\n int j = pi[i-1];\n while (j > 0 && t.charAt(j) != t.charAt(i)) j = pi[j - 1];\n if (j == 0 && t.charAt(0) != t.charAt(i)) pi[i] = 0;\n else pi[i] = j + 1;\n }\n int j = 0;\n List<Integer> res = new ArrayList<>();\n for (int i = 0; i < m; ++i) {\n while (j >= n || (j > 0 && s.charAt(i) != t.charAt(j))) j = pi[j - 1];\n if (s.charAt(i) == t.charAt(j)) j++;\n if (j == n) res.add(i-n+1);\n }\n return res;\n }\n}\nclass Solution {\n public long pow(long a, long b, int M) {\n if (b == 0) return 1;\n if ((b & 1) == 0) return pow(a * a % M, b >> 1, M);\n return a * pow(a * a % M, b >> 1, M) % M;\n }\n public int numberOfWays(String s, String t, long k) {\n int n = s.length(), M = 1000000007;\n List<Integer> pos = new StringAlgorithm().kmp(s + s.substring(0, n-1), t);\n long []f_k = {0, 0};\n f_k[1] = (pow(n-1, k, M) + (k % 2 * 2 - 1) + M) % M * pow(n, M-2, M) % M;\n f_k[0] = (f_k[1] - (k % 2 * 2 - 1) + M) % M;\n int res = 0;\n for (Integer p: pos) {\n if (p == 0) res = (res + (int)f_k[0]) % M;\n else res = (res + (int)f_k[1]) % M;\n }\n return res;\n }\n}\n```\n``` Python3 []\nclass Solution:\n def kmp(self, s, t):\n pi, res = [0 for i in range(len(t))], []\n for i in range(1, len(t)):\n j = pi[i-1]\n while j > 0 and t[j] != t[i]: j = pi[j-1]\n pi[i] = 0 if j == 0 and t[0] != t[i] else j + 1\n m, n, j = len(s), len(t), 0\n for i in range(m):\n while j >= n or j > 0 and s[i] != t[j]: j = pi[j-1]\n if s[i] == t[j]: j += 1\n if j == n: res.append(i - n + 1)\n return res\n def numberOfWays(self, s: str, t: str, k: int) -> int:\n n, M = len(s), 10**9 + 7\n pos = self.kmp((s+s)[:-1], t)\n f_k = [0, 0]\n f_k[1] = (pow(n-1, k, M) - (-1)**k + M) * pow(n, M-2, M) % M\n f_k[0] = (f_k[1] + (-1)**k + M) % M\n return sum(f_k[not not p] for p in pos) % M\n``` | 51 | 0 | ['Math', 'String Matching', 'C++', 'Java', 'Python3'] | 10 |
string-transformation | Solutions with C++, Java and python | solutions-with-c-java-and-python-by-cpcs-6u26 | Intuition\nDP, Z-algorithm, Fast mod.\n\n# Approach\n1. How to represent a string?\nEach operation is just a rotation. Each result string can be represented by | cpcs | NORMAL | 2023-09-10T04:01:59.733285+00:00 | 2023-09-10T04:01:59.733315+00:00 | 8,264 | false | # Intuition\nDP, Z-algorithm, Fast mod.\n\n# Approach\n1. How to represent a string?\nEach operation is just a rotation. Each result string can be represented by an integer from 0 to n - 1. Namely, it\'s just the new index of s[0].\n\n2. How to find the integer(s) that can represent string t?\nCreate a new string s + t + t (length = 3 * n).\nUse Z-algorithm (or KMP), for each n <= index < 2 * n, calculate the maximum prefix length that each substring starts from index can match, if the length >= n, then (index - n) is a valid integer representation.\n\n3. How to get the result?\nIt\'s a very obvious DP.\nIf we use an integer to represent a string, we only need to consider the transition from zero to non-zero and from non-zero to zero. In other words, all the non-zero strings should have the same result.\n\nSo let dp[t][i = 0/1] be the number of ways to get the zero/nonzero string\nafter excatly t steps.\nThen\ndp[t][0] = dp[t - 1][1] * (n - 1). \nAll the non zero strings can make it.\n\ndp[t][1] = dp[t - 1][0] + dp[t - 1] * (n - 2). \nFor a particular non zero string, all the other non zero strings and zero string can make it.\n\nWe have dp[0][0] = 1 and dp[0][1] = 0\n\n4. Use matrix multiplication.\n\nHow to calculate dp[k][x = 0, 1] faster?\n\nUse matrix multiplication\n\nvector (dp[t - 1][0], dp[t - 1][1])\n\nmultiplies matrix\n\n[0 1]\n[n - 1 n - 2]\n\n== vector (dp[t][0], dp[t - 1][1]).\n\nSo we just need to calculate the kth power of the matrix which can be done by fast power algorith.\n\n\n\n\n# Complexity\n- Time complexity:\nO(n + logk)\n\n- Space complexity:\nO(n)\n\n# Code\nC++\n```\nclass Solution {\nconst int M = 1000000007;\n\nint add(int x, int y) {\n if ((x += y) >= M) {\n x -= M;\n }\n return x;\n}\n\nint mul(long long x, long long y) {\n return x * y % M;\n}\n \n \nvector<int> getz(const string& s) {\n const int n = s.length();\n vector<int> z(n);\n for (int i = 1, left = 0, right = 0; i < n; ++i) {\n if (i <= right && z[i - left] <= right - i) {\n z[i] = z[i - left];\n } else {\n for (z[i] = max(0, right - i + 1); i + z[i] < n && s[i + z[i]] == s[z[i]]; ++z[i])\n ; \n }\n if (i + z[i] - 1 > right) {\n left = i;\n right = i + z[i] - 1;\n }\n }\n return z;\n}\n \nvector<vector<int>> mul(const vector<vector<int>> &a, const vector<vector<int>> &b) {\n const int m = a.size(), n = a[0].size(), p = b[0].size();\n vector<vector<int>> r(m, vector<int>(p));\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n for (int k = 0; k < p; ++k) {\n r[i][k] = add(r[i][k], mul(a[i][j], b[j][k]));\n }\n }\n }\n return r;\n}\n \nvector<vector<int>> pow(const vector<vector<int>> &a, long long y) {\n const int n = a.size();\n vector<vector<int>> r(n, vector<int>(n));\n for (int i = 0; i < n; ++i) {\n r[i][i] = 1;\n }\n auto x = a;\n for (; y; y >>= 1) {\n if (y & 1) {\n r = mul(r, x);\n }\n x = mul(x, x);\n }\n return r;\n}\n \npublic:\n int numberOfWays(string s, string t, long long k) {\n const int n = s.length();\n const auto dp = pow({{0, 1}, {n - 1, n - 2}}, k)[0];\n s.append(t);\n s.append(t);\n const auto z = getz(s);\n const int m = n + n;\n int r = 0;\n for (int i = n; i < m; ++i) {\n if (z[i] >= n) {\n r = add(r, dp[!!(i - n)]);\n }\n }\n return r;\n }\n};\n```\n\nJava\n```\nclass Solution {\n private static final int M = 1000000007;\n\n private int add(int x, int y) {\n if ((x += y) >= M) {\n x -= M;\n }\n return x;\n }\n\n private int mul(long x, long y) {\n return (int) (x * y % M);\n }\n\n private int[] getZ(String s) {\n int n = s.length();\n int[] z = new int[n];\n for (int i = 1, left = 0, right = 0; i < n; ++i) {\n if (i <= right && z[i - left] <= right - i) {\n z[i] = z[i - left];\n } else {\n int z_i = Math.max(0, right - i + 1);\n while (i + z_i < n && s.charAt(i + z_i) == s.charAt(z_i)) {\n z_i++;\n }\n z[i] = z_i;\n }\n if (i + z[i] - 1 > right) {\n left = i;\n right = i + z[i] - 1;\n }\n }\n return z;\n }\n\n private int[][] matrixMultiply(int[][] a, int[][] b) {\n int m = a.length, n = a[0].length, p = b[0].length;\n int[][] r = new int[m][p];\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < p; ++j) {\n for (int k = 0; k < n; ++k) {\n r[i][j] = add(r[i][j], mul(a[i][k], b[k][j]));\n }\n }\n }\n return r;\n }\n\n private int[][] matrixPower(int[][] a, long y) {\n int n = a.length;\n int[][] r = new int[n][n];\n for (int i = 0; i < n; ++i) {\n r[i][i] = 1;\n }\n int[][] x = new int[n][n];\n for (int i = 0; i < n; ++i) {\n System.arraycopy(a[i], 0, x[i], 0, n);\n }\n while (y > 0) {\n if ((y & 1) == 1) {\n r = matrixMultiply(r, x);\n }\n x = matrixMultiply(x, x);\n y >>= 1;\n }\n return r;\n }\n\n public int numberOfWays(String s, String t, long k) {\n int n = s.length();\n int[] dp = matrixPower(new int[][]{{0, 1}, {n - 1, n - 2}}, k)[0];\n s += t + t;\n int[] z = getZ(s);\n int m = n + n;\n int result = 0;\n for (int i = n; i < m; ++i) {\n if (z[i] >= n) {\n result = add(result, dp[i - n == 0 ? 0 : 1]);\n }\n }\n return result;\n }\n}\n```\n\nPython\n```\nclass Solution:\n M: int = 1000000007\n\n def add(self, x: int, y: int) -> int:\n x += y\n if x >= self.M:\n x -= self.M\n return x\n\n def mul(self, x: int, y: int) -> int:\n return int(x * y % self.M)\n\n def getZ(self, s: str) -> List[int]:\n n = len(s)\n z = [0] * n\n left = right = 0\n for i in range(1, n):\n if i <= right and z[i - left] <= right - i:\n z[i] = z[i - left]\n else:\n z_i = max(0, right - i + 1)\n while i + z_i < n and s[i + z_i] == s[z_i]:\n z_i += 1\n z[i] = z_i\n if i + z[i] - 1 > right:\n left = i\n right = i + z[i] - 1\n return z\n\n def matrixMultiply(self, a: List[List[int]], b: List[List[int]]) -> List[List[int]]:\n m = len(a)\n n = len(a[0])\n p = len(b[0])\n r = [[0] * p for _ in range(m)]\n for i in range(m):\n for j in range(p):\n for k in range(n):\n r[i][j] = self.add(r[i][j], self.mul(a[i][k], b[k][j]))\n return r\n\n def matrixPower(self, a: List[List[int]], y: int) -> List[List[int]]:\n n = len(a)\n r = [[0] * n for _ in range(n)]\n for i in range(n):\n r[i][i] = 1\n x = [a[i][:] for i in range(n)]\n while y > 0:\n if y & 1:\n r = self.matrixMultiply(r, x)\n x = self.matrixMultiply(x, x)\n y >>= 1\n return r\n\n def numberOfWays(self, s: str, t: str, k: int) -> int:\n n = len(s)\n dp = self.matrixPower([[0, 1], [n - 1, n - 2]], k)[0]\n s += t + t\n z = self.getZ(s)\n m = n + n\n result = 0\n for i in range(n, m):\n if z[i] >= n:\n result = self.add(result, dp[0] if i - n == 0 else dp[1])\n return result\n```\n | 41 | 0 | ['Python', 'C++', 'Java', 'Python3'] | 8 |
string-transformation | Rabin-Karp and Recurrence Relation | rabin-karp-and-recurrence-relation-by-je-ujrd | Intuition\nClearly, t must be some rotation of s. Moreover, we see that if t is s rotated by some amount i, the problem essentially asks how many ways we can su | jeffreyhu8 | NORMAL | 2023-09-10T04:01:29.811268+00:00 | 2023-09-13T16:25:02.291855+00:00 | 2,351 | false | # Intuition\nClearly, `t` must be some rotation of `s`. Moreover, we see that if `t` is `s` rotated by some amount `i`, the problem essentially asks how many ways we can sum up `k` integers in `[1, n)` that add up to `i` modulo `n`, which is a type of dynamic programming problem. The problem reduces to\n1. Finding which rotations of `s` result in `t`.\n2. Finding how many ways `k` integers in `[1, n)` can add up to some `i` modulo `n`.\n\n# Approach\nFinding all occurences of `s` in `2 * t` (i.e. finding all `i` such that `t` is a rotation of `s`) can be done with Rabin-Karp or other substring search algorithms.\n\nFinding how many ways `k` integers in `[1, n)` can add up to some `i` modulo `n` can be reduced to solving a recurrence relation with characteristic roots.\n\n## Recurrence Relation\n\nEdit: Here is the recurrence relation and how to solve it.\n\nLet $$f(k, 0)$$ be the number of ways to rotate `s` by 0 after $$k$$ operations. Let $$f(k, 1)$$ be the number of ways to rotate `s` by some fixed nonzero amount after $$k$$ operations.\n\nWith some careful reasoning, we have\n1. $$f(k, 0) = (n - 1)\\cdot f(k - 1, 1)$$\n2. $$f(k, 1) = f(k - 1, 0) + (n - 2)\\cdot f(k - 1, 1).$$\n\nSee [cpcs\'s solution](https://leetcode.com/problems/string-transformation/solutions/4024648/solutions-with-c-java-and-python/) for the reasoning behind this recurrence relation.\n\nFrom (1), we have \n3. $$f(k - 1, 0) = (n - 1)\\cdot f(k - 2, 1).$$\n\nSubstituting (3) into (2) and rearranging terms, we get $$f(k, 1) = (n - 2)\\cdot f(k - 1, 1) + (n - 1)\\cdot f(k - 2, 1).$$\n\nThe [characteristic equation](https://discrete.openmathbooks.org/dmoi2/sec_recurrence.html) is $$x^2 = (n - 2)x + (n - 1).$$ Solving this quadratic gives $$x=n-1,-1.$$\n\nThus, the solution to the recurrence relation is of the form $$f(k, 1) = \\alpha(n-1)^k+\\beta(-1)^k.$$\n\nPlugging in the initial conditions $$f(0, 1) = 0, f(1, 1) = 1$$ gives $$\\alpha=1/n, \\beta=-1/n$$, yielding the solution $$f(k, 1) = \\frac{(n - 1)^k - (-1)^k}n$$.\n\nFrom (1) and some manipulation, we have\n$$f(k, 0) = (n - 1)f(k - 1, 1)$$\n$$= (n - 1)\\cdot \\frac{(n - 1)^{k - 1} - (-1)^{k - 1}}n$$\n$$= \\frac{(n - 1)\\cdot (n - 1)^{k - 1} - (n - 1)\\cdot (-1)^{k - 1}}n$$\n$$= \\frac{(n - 1)^k - (n - 1)\\cdot (-1)^{k - 1}}n$$\n$$= \\frac{(n - 1)^k - n \\cdot (-1)^{k - 1} + (-1)^{k - 1}}n$$\n$$= \\frac{(n - 1)^k + n \\cdot (-1)^k - (-1)^k}n$$\n$$= \\frac{(n - 1)^k - (-1)^k + n \\cdot (-1)^k}n$$\n$$= \\frac{(n - 1)^k - (-1)^k}n + (-1)^k.$$\n\n# Complexity\n- Time complexity: $$O(n + \\lg k)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\nEdit: the solution has been updated to take $$O(n + \\lg k)$$ time.\n```py\nclass Solution:\n MOD = 10 ** 9 + 7\n P = 31\n PMOD = 496822652529863993\n\n def numberOfWays(self, s: str, t: str, k: int) -> int:\n n = len(s)\n\n sHash = 0\n for c in s:\n sHash *= Solution.P\n sHash += ord(c) - ord(\'a\')\n sHash %= Solution.PMOD\n\n tHash = 0\n for c in t:\n tHash *= Solution.P\n tHash += ord(c) - ord(\'a\')\n tHash %= Solution.PMOD\n\n # Rabin-Karp\n res = 0\n largestPower = pow(Solution.P, n - 1, Solution.PMOD)\n fk1 = (pow((n - 1), k, Solution.MOD) - (-1) ** k) * pow(n, -1, Solution.MOD) # f(k, 1)\n for i, c in enumerate(t):\n # cyclic substring found\n if sHash == tHash:\n res += fk1 if i != 0 else fk1 + (-1) ** k\n res %= Solution.MOD\n\n # shift t\n intC = ord(c) - ord(\'a\')\n tHash -= largestPower * intC\n tHash = (tHash % Solution.PMOD + Solution.PMOD) % Solution.PMOD\n\n tHash *= Solution.P\n tHash += intC\n tHash %= Solution.PMOD\n\n return res\n``` | 26 | 0 | ['String', 'Python3'] | 4 |
string-transformation | Java Solution With Detailed Explanation | java-solution-with-detailed-explanation-pst4o | Background\n\nRemoving the suffix of length l and appending to the front is same as a right shift. So after k operations. S would just be right shifted some num | profchi | NORMAL | 2023-09-10T04:02:17.348402+00:00 | 2023-09-13T04:03:24.608050+00:00 | 2,480 | false | # Background\n\nRemoving the suffix of length l and appending to the front is same as a right shift. So after k operations. S would just be right shifted some number of times.\n\n# Solution\n\nFirst ignore the constraint for k and n. Let n be the length of s. We can solve this easily with a 2 dimensional dp[kTimes][shifts]. shift is the total shifts mod n, and KTimes is the number of shift operations performed. dp[a][b] would be sum of all dp[a - 1] except of dp[a - 1][b] since we cannot shift by n or 0 but we can shift from other indexes.\n\nFor s of length 4 we see the dp generated \ndp[0] = [1, 0, 0, 0]\ndp[1] = [0, 1, 1, 1]\ndp[2] = [3, 2, 2, 2]\n\nNotice based on the values and how we compute the results, dp[a][0] would be different while the rest would be same. Now we can condense dp[a] to an array with two values where the first represents dp[a][0] and the second represents dp[a][1 \u2026. n-1]\n\ndp[0] = [1, 0,]\ndp[1] = [0, 1,]\ndp[2] = [3, 2,]\n\nFrom this we can compute the recurrence matrix relation\n\n```\n\nX1. \t0 n-1 \t\tX0\n\t=\ny1 \t1 n - 2\t\tY0\n```\n\n\nHere Xa is the value of the first value after a operations and Ya is the second value after a operations \nThe root matrix that is when k = 1 is (1, n -2)(0, n - 1) because X(a + 1) = (n - 1) * Ya, Y(a + 1) = Xa + (n - 2) * Ya\n\nWith this recurrence relation, we can then use matrix exponentiation to find the number of ways for each net Shift after k operations\n\n\nWe check each net shifts from 0 to n if right shifting by that of s results in t. If it does add the ways to arrive at that shift to the final result.\n\nWe can check if right shifting in O(n) using rolling hash\n\nTotal time complexity is O(n + log K)\n\nPlease upvote if you like the Solution :) \n\n\n# Code\n```\n\n\nclass Solution {\n \n long mod = 1_000_000_007;\n \n public int numberOfWays(String s, String t, long k) {\n \n \n \n long hash = 0;\n \n //long [] pow = new long [s.length()];\n long mul = 1;\n int idx = 0;\n\n long mul2 = 1;\n\n long hash2 = 0; \n long sHash2 = 0;\n \n for (char c : t.toCharArray()) {\n\n mul *= 26;\n mul %= mod;\n\n mul2 *= 27;\n mul2 %= mod;\n \n hash *= 26;\n hash += c - \'a\';\n hash %= mod;\n\n hash2 *= 27;\n hash2 += c - \'a\';\n hash2 %= mod;\n }\n \n long sHash = 0;\n \n for (char c : s.toCharArray()) {\n sHash *= 26;\n sHash += c - \'a\';\n sHash %= mod;\n\n sHash2 *= 27;\n sHash2 += c - \'a\';\n sHash2 %= mod;\n }\n \n List<Integer> index = new ArrayList<>();\n \n long other, other2;\n \n int n = s.length();\n \n \n for (int i = 0, j = s.length() - 1; i < s.length(); ++i) {\n if (sHash == hash && sHash2 == hash2)\n index.add((n - i) % n);\n \n sHash *= 26;\n sHash2 *= 27;\n \n sHash += mod;\n sHash2 += mod;\n\n other = s.charAt(i) - \'a\';\n other2 = other * mul;\n other2 %= mod;\n sHash -= other2;\n sHash += other;\n\n other = s.charAt(i) - \'a\';\n other2 = other * mul2;\n other2 %= mod;\n sHash2 -= other2;\n sHash2 += other;\n\n \n sHash %= mod;\n sHash2 %= mod;\n }\n \n \n long result = 0;\n \n long [][] root = new long [][] {{0, n - 1}, {1 , n - 2}};\n \n long [][] pow = powerExp(root, k);\n \n long a = pow[0][0] * 1;\n long b = pow[1][0] * 1;\n\n //System.out.println(index);\n \n for (int num : index) {\n result += num == 0 ? a : b;\n \n result %= mod;\n }\n \n \n return (int)result;\n \n }\n \n private long [][] powerExp (long [][] mat, long pow) {\n\t\tMap<Long, long [][]> map = new HashMap<>();\n\t\t\n\t\tlong current = 1;\n\t\tlong [][] val = mat;\n\t\tlong [][] result = new long [mat.length][mat.length];\n\t\t\n\t\tfor (int i = 0; i < mat.length; ++i) {\n\t\t\tresult[i][i] = 1;\n\t\t}\n\t\t\n\t\twhile (current <= pow) {\n\t\t\tmap.put(current, val);\n\t\t\t\n\t\t\tval = multiplyMat(val, val);\n\t\t\tcurrent *= 2;\n\t\t}\n\t\t\n\t\twhile (current > 1) {\n\t\t\tcurrent /= 2;\n\t\t\t\n\t\t\tif (pow >= current) {\n\t\t\t\tpow -= current;\n\t\t\t\tresult = multiplyMat(result, map.get(current));\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn result;\n\t}\n\t\n\t\n\t\n\tprivate long [][] multiplyMat(long [][] mat1, long [][] mat2) {\n\t\tlong [][] result = new long [mat1.length][mat2[0].length];\n\t\tlong sum = 0;\n\t\t\n\t\tfor (int i = 0; i < mat1.length; ++i) {\n\t\t\tfor (int j = 0; j < mat2[0].length; ++j) {\n\t\t\t\tsum = 0;\n\t\t\t\t\n\t\t\t\tfor (int k = 0; k < mat1.length; ++k) {\n\t\t\t\t\tsum += mat1[i][k] * mat2[k][j];\n\t\t\t\t\tsum %= mod;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tsum %= mod;\n\t\t\t\tresult[i][j] = sum;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn result;\n\t}\n}\n\n```\n | 18 | 0 | ['Rolling Hash', 'Matrix', 'Java'] | 3 |
string-transformation | 😵💫Complex Maths || Derivation || Z-Algo || | complex-maths-derivation-z-algo-by-jainw-dned | Sorry for such messy mathematics , \n### But it is what it is !!\n\n\n\n# Code\n\n#define ll long long\nclass Solution {\npublic:\n int mod=1e9+7;\n\n ll | JainWinn | NORMAL | 2023-09-10T18:40:33.505544+00:00 | 2023-09-10T18:42:00.192610+00:00 | 667 | false | #### Sorry for such messy mathematics , \n### But it is what it is !!\n\n\n\n# Code\n```\n#define ll long long\nclass Solution {\npublic:\n int mod=1e9+7;\n\n ll calcpower(ll x, ll n)\n {\n if (n == 1)\n {\n return x;\n }\n ll temp = calcpower(x, n / 2);\n if (n & 1)\n {\n return ((((x * temp) % mod) * temp) % mod);\n }\n return (temp * temp) % mod;\n }\n\n // Fermat\'s Little Theorem : a^p=a mod(p) => a^(p-2)=(a^-1)mod(p)\n ll modinv(ll num)\n {\n return calcpower(num, mod - 2);\n }\n\n //Z-Algorithm\n vector<int> calculateZ(string &s){\n vector<int> z(s.size(),0);\n int l=0;\n int r=0;\n for(int k=1 ; k<s.size() ; k++){\n if(k>r){\n l=r=k;\n while(r<s.size() && s[r]==s[r-l]){\n r++;\n }\n z[k]=r-l;\n r--;\n }\n else{\n int k1=k-l;\n if(z[k1]<r-k+1){\n z[k]=z[k1];\n }\n else{\n l=k;\n while(r<s.size() && s[r]==s[r-l]){\n r++;\n }\n z[k]=r-l;\n r--;\n }\n }\n }\n return z;\n }\n\n int numberOfWays(string s, string t, long long k) {\n if(s.size()!=t.size()){\n return 0;\n }\n string temp=t;\n temp+=\'$\';\n temp+=s;\n temp+=s;\n\n vector<int> z=calculateZ(temp);\n vector<long long> v;\n int n=s.size();\n if(k%2==0){\n v.resize(n,(((calcpower(n-1,k)-1)*modinv(n))%mod));\n v[0]+=1;\n v[0]%=mod;\n }\n else{\n v.resize(n,(((calcpower(n-1,k)+1)*modinv(n))%mod));\n v[0]-=1;\n v[0]+=mod;\n v[0]%=mod;\n }\n\n int ans=0;\n for(int i=0 ; i<z.size() ; i++){\n if(z[i]==t.size()){\n if(i-t.size()-1>=0 && i-t.size()-1<n){\n ans+=v[i-t.size()-1];\n }\n ans%=mod;\n }\n }\n\n return ans%mod;\n }\n};\n``` | 10 | 0 | ['Math', 'String Matching', 'C++'] | 2 |
string-transformation | Patterns, KMP and maths | python No matrix exponentiation | Explanation of modular arithmetic | patterns-kmp-and-maths-python-no-matrix-ip7rv | Approach\nFirst, let\'s define the possible rotations of $s$ in which $s_i = t$, with $s_i$ being $s$ rotated $i$ to the left. We can obtain all the possible ro | BetoSCL | NORMAL | 2023-09-10T04:10:20.295160+00:00 | 2023-09-10T22:34:46.946637+00:00 | 1,208 | false | # Approach\nFirst, let\'s define the possible rotations of $s$ in which $s_i = t$, with $s_i$ being $s$ rotated $i$ to the left. We can obtain all the possible rotations using the Knuth-Morris-Pratt (KMP) algorithm. By doubling the string $s$ and finding all occurrences of $t$, we identify these rotations.\n\nAfter presenting the solution, it\'s important to understand that we are working with arithmetic modulo. This means that achieving a rotation of $i$ corresponds to finding a sequence of operations whose sum, when taken modulo $n$, results in $i$. For example, if we have a string of size $n=5$, and we need a rotation of $3$, we can achieve this with a single rotation of $3$. However, we can also reach the same rotation of $3$ with two operations: $4$ and $4$. This is because $4 + 4 \\mod 5 = 3$ . so the sequence $[4,4]$ will count as a valid sequence for the remainder $3$\n\n\nNow that we have the necessary rotation, we need to determine the number of ways we can achieve that rotation using exactly $k$ operations. Initially, we might consider a dynamic programming (DP) approach where $DP[x][k]$ represents the number of ways to obtain rotation(remainder) $x$ using $k$ operations:\n\n$$\nDP[x][k] = \\sum_{i=1}^{n-1} DP[(x-i)\\%n][k-1]\n$$\n\nHowever, this solution may not be feasible for large limits, as it requires a lot of calculations. So, let\'s look for a more efficient approach.\n\nConsider the behavior of this DP. For example for an arbitrary string of length $5$ Initially, we have $DP[i][1] = [0, 1, 1, 1, 1]$. If we examine each operation that we can made as the $k$ operation individually, we can observe that we introduce new remainders as follows:\n\n- If we add an operation of length $1$, the new possible values will be: $[1, 0, 1, 1, 1]$\n- If we add an operation of length $2$, the new possible values will be: $[1, 1, 0, 1, 1]$\n- If we add an operation of length $3$, the new possible values will be: $[1, 1, 1, 0, 1]$\n- And with an operation of length $4$, the new values will be: $[1, 1, 1, 1, 0]$\n\n> View arrays as frequency arrays for each remainder and these will be summed at the end.\n\nSo at the end for $DP[i][2]$ we get: \n$DP[i][2] = [4,3,3,3,3]$\n\nAnd $DP[i][3] = [12,13,13,13,13]$ \n\nThis behavior occurs because the previous DP values are shifted when we attempt to add an operation of type $i$. The way in which the total sum of possible sequences introducing another operation increases is in terms of powers of $n-1$ because there are $[1, n-1]$ valid operations so $n-1$ ways to shift.\n\nTherefore, the total possible ways for all remainders at operation $k$ will be $(n-1)^k$. However, there is a caveat. If you calculate the sums and complete the process to obtain, for example, $DP[i][2]$, you\'ll notice that there are some numbers with one more or one fewer possible sequences. This discrepancy occurs because of the gaps left behind since we cannot perform operations of length $0$ or $n$ and since we need to distribute $(n-1)^k$ in $n$ spaces which cannot be equal distributed.\n\nWith this insight, let\'s examine the array for different values of $k$. You\'ll discover that the array takes on the following patterns:\n\n- $[x+1, x, x, x, x, x,\\dots]$ for even $k$\n- $[x-1, x, x, x, x, x,\\dots]$ for odd $k$\n\nNow, we can use some maths to determine the value of $x$. As mentioned earlier, the total sum increases in terms of powers of $n-1$. The equations look like this:\n\nFor even $k$:\n$$\nx \\cdot (n-1) + (x+1) = (n-1)^k\n$$\n\nFor odd $k$:\n$$\nx \\cdot (n-1) + (x-1) = (n-1)^k\n$$\n\nBy rearranging these equations, we can isolate $x$:\n\nFor even $k$:\n$$\nx = \\frac{(n-1)^k - 1}{n}\n$$\nFor odd $k$: \n$$\nx = \\frac{(n-1)^k + 1}{n}\n$$\n\nSo, that\'s it! We can determine how many ways we have to form $i$ in $k$ operations. The last step is to sum up those values of $i$ for which the rotation $s_i = t$ holds.\n\n# Explanation of the pattern $x+1,x,x,x,x$ and why the parity matters. \n\nThe pattern can be obtained using arithmetic modulo. First, let\'s define a property: \n\nAll values of $x$ that are congruent with $y$, i.e., $x \\equiv y \\mod n$, will have the same remainder as $y$ when raised to an arbitrary power $k$, i.e., $x^k \\equiv y^k \\mod n$ this is also equivalent to $x^k \\equiv (x +pn)^k \\mod n$.\n\nWith this property in mind, we can derive an equivalence for even values of $k$ in our problem.\n\n**When $k$ is even:**\n$$(n-1)^k = (n-1)^{2m} \\equiv ((n-1)^2)^m \\ (\\text{mod } n)$$\n\n$$((n-1)^2)^m = (n^2 -2n +1)^m$$\n\nSolving the remainder inside the parenthesis, we find that \n$n^2 -2n +1 \\equiv 1 \\mod n$\n\nSo we can substitute:\n$$(n-1)^k \\equiv 1^m \\mod n$$\n$$= (n-1)^k \\equiv 1 \\mod n$$\n\n**When $k$ is odd:**\n$$(n-1)^k = (n-1)^{2m+1} \\equiv (n-1)((n-1)^2)^m \\ (\\text{mod } n)$$\n\nNow that we know the case for $k$ being even, we get:\n$$(n-1)^k = (n-1)^{2m+1} \\equiv (n-1)(1) \\ (\\text{mod } n)$$\n$$(n-1)^k \\equiv (n-1) \\mod n$$\n\n\nNow, returning to our array $DP[i][k]$, we\'ve established that their total sum increases in terms of powers of $n-1$. However, due to the nature of the distribution, it\'s not exactly the same for each space. This discrepancy occurs because we always leave a remainder when distributing $(n-1)^k$ into $n$ spaces.\n\nTherefore, considering that the distribution is nearly uniform across all spaces, we can approximate it by distributing $\\lfloor \\frac{(n-1)^k}{n} \\rfloor$ for each space.\n\nLet\'s denote:\n- $x = \\lfloor \\frac{(n-1)^k}{n} \\rfloor$\n- $v = [x, x, x, x, x, x]$\n\nThe reason why only $v[0]$ differs from others is because, at the beginning when $k=1$, we cannot have a remainder of $0$ since operations $0$ or $n$ don\'t exist. Thus, for even $k$, we have a remainder of $1$, so we place the remainder in $v[0]$, resulting in $v = [x+1, x, x, x, x, x]$.\n\nOn the other hand, when $k$ is odd, the remainder is $n-1$. In this case, we distribute the remainder evenly among all $v[i]$ except $v[0]$, resulting in $v = [x, x+1, x+1, x+1, x+1, x+1]$. To maintain a formula similar to the even case, we adjust $v$ to $v = [x-1, x, x, x, x, x]$.\n\n# Complexity\n- Time complexity:\n- $O(n log(k))$\n\n\n# Code\n```\nclass Solution:\n def numberOfWays(self, s: str, t: str, k: int) -> int: \n n = len(s)\n\n # KMP to know the valid rotations \n def pFunction(v):\n n = len(v)\n p = [0]*n\n for i in range(1,n):\n j = p[i-1]\n while j > 0 and v[j] != v[i] :\n j = p[j - 1]\n \n if v[j] == v[i]:\n j+=1\n p[i] = j \n return p\n \n def getValidRotations(a,b):\n tmp = b+"#"+a+a\n \n p = pFunction(tmp) \n \n positions = []\n for i in range(n+1,len(tmp)):\n if p[i] == n:\n rot = (i-(n-1))-(n+1)\n if rot<n: \n positions.append(rot)\n return positions\n \n # Binary exponentiation \n mod = 10**9 + 7\n def bin_pow(a,b):\n x = 1\n while b: \n if b&1: \n x*=a \n x%=mod\n a*=a\n a%=mod\n b>>=1\n return x \n \n # Modular inverse, since we have a division in our formula we need to use the modular inverse, we can use this mode since mod is a prime.\n def inv(x):\n return bin_pow(x,mod-2) \n\n # v[i] says how many sequences we have for the remainder i with k operations\n v = []\n if k%2 == 0:\n v = [((bin_pow(n-1,k)-1)* inv(n)) %mod]*n\n v[0]+=1\n v[0]%=mod\n else:\n v = [((bin_pow(n-1,k)+1)* inv(n)) %mod]*n\n v[0]-=1\n if v[0]<0:\n v[0]+=mod\n \n ans = 0\n for p in getValidRotations(s,t): \n ans+=v[p]\n ans%=mod\n \n \n return ans \n``` | 9 | 0 | ['Python3'] | 2 |
string-transformation | [QUICK MAFS] The math explained REAL simply | quick-mafs-the-math-explained-real-simpl-kmiz | Intuition\nSo first off, as noted in many other solutions, this fancy schmancy operation is equivalent to rotating the string by a certain amount $\color{pink}i | gtsmarmy | NORMAL | 2023-09-13T01:53:49.674686+00:00 | 2023-09-13T02:00:07.895090+00:00 | 537 | false | # Intuition\nSo first off, as noted in many other solutions, this fancy schmancy operation is equivalent to rotating the string by a certain amount $\\color{pink}i$. What\'s nice about framing it in this manner is that you can associate every rotated string (there are $\\color{lime} n-1$ of them) with an integer $\\color{pink} i, 0 \\leqslant i < n$. All this integer $\\color{pink} i$ really represents is the starting index of the string.\n\nEXAMPLES:\n$s = $`"abbc"`, then these are the corresponding $\\color{pink} i \\to$ Rotated States:\n\n| $\\color{pink} i$ | Rotated State |\n| -------- | ------- |\n| 0 | `abbc` |\n| 1 | `cabb` |\n| 2 | `bcab` |\n| 3 | `bbca` |\n\nok, now onto the maths. \nLet\'s define a function $\\color{yellow} f_k(i)$ that represents the number of ways to reach $\\color{pink} i$ after $\\color{cyan} k$ operations. \n\n### Base case\nClearly, $\\color{yellow} f_0(0) = 1$. If you don\'t perform any operations then the starting string will be the only string you can reach. As a consequence, $\\color{yellow} f_0(j) = 0, j \\neq 0$. \n\n### Recursion\nNow let\'s suppose we are at $\\color{yellow} f_k(i)$, how can we get here? We note that we are **ALMOST** given full freedom of rotation. It\'s just we can\'t rotate by $0$ or $n$. All this means is that the string MUST change each turn, i.e. the associated index $\\color{pink} i$ must change. So we have\n$$\\color{yellow} f_k(i) = f_{k-1}(0) + \\dotsc + f_{k-1}(i-1) + f_{k-1}(i+1) + \\dotsc + f_{k-1}(n-1)$$\nNote that we skip $\\color{yellow} f_{k-1}(i)$, this is the only string from the previous move that is the same. We can rewrite the equation above as follows:\n\n$$\\Large \\color{yellow} f_k(i) = \\left(\\sum\\limits_{j=0}^{n-1} f_{k-1}(j) \\right) - f_{k-1}(i) $$\n\nNow we just need to solve this recurrence. It\'s not that bad! So first off we notice that no matter what $\\color{pink} i$ we are at, the quantity $$\\large \\color{yellow} \\sum\\limits_{j=0}^{n-1} f_{k-1}(j)$$ only depends on $\\color{cyan} k$. Let\'s call it $\\large \\color{tan} S_{k-1}$ accordingly.\n\nSo just to reiterate, we have\n$$\\Large \\color{yellow} f_k(i) =S_{k-1} - f_{k-1}(i) $$\n\nThis looks a bit annoying to solve but there\'s a **VERY** neat trick we can employ here.\n\nConsider\n\n$$\\Large \\color{turquoise} \\sum\\limits_{i=0}^{n-1} \\color{yellow} f_k(i) = \\color{turquoise} \\sum\\limits_{i=0}^{n-1} \\color{yellow} \\left(S_{k-1} - f_{k-1}(i)\\right)$$\n\nThe LHS is by definition $\\large \\color{turquoise} S_k$, and the RHS can be broken up and evaluated similarly as $\\large \\color{turquoise} nS_{k-1} - S_{k-1}$\n\nAll in all, we get\n$\\large \\color{turquoise} S_k = (n-1)S_{k-1}$\n\nSince we have $\\large \\color{turquoise} S_0 = 1$ (this follows from the base case), we can solve the simple recurrence to yield\n$\\large \\color{turquoise} S_k = (n-1)^k$\n\nSubstituting that in to our original $\\color{yellow} f_k(i)$ formula yields\n\n$$\\Large \\color{yellow} f_k(i) = (n-1)^{k-1} - f_{k-1}(i) $$\n\nClearly, this recurrence relation only depends on $\\color{cyan} k$, so let\'s make a change. \n$\\large \\color{lime} g(k) = f_k(i)$\n\nThen, we get\n\n$\\large \\color{lime} g(k) = (n-1)^{k-1} - g(k-1)$\n\nNow there are a few ways to proceed from here. You could list $\\large \\color{lime} g(k), g(k-1), g(k-2)$, substitute them into each other and notice a pattern, or you could be a rigorous stickler like I am going to be.\n\nSo, let\'s get our functions on one side and weird constant thing on the other.\n\n$\\large \\color{lime} g(k) + g(k-1) = (n-1)^{k-1}$\n\nThe motivation for this next step will be outlined shortly.\n\nLet $\\large \\color{orange} h(k) = (-1)^k g(k)$, then we get\n\n$\\large \\color{orange} h(k) - h(k-1) = (-1)^k (n-1)^{k-1}$\n\nNow, we do the same trick from before.\n\n\n$$\\Large \\color{turquoise} \\sum\\limits_{t=1}^{k}\\color{orange} \\left(h(t) - h(t-1)\\right) = \\color{turquoise} \\sum\\limits_{t=1}^{k} \\color{orange} (-1)^t (n-1)^{t-1}$$ (Note: I renamed the variables to avoid confusion)\n\nNotice how the left side telescopes? It\'s very nice! The right side is an *annoying* finite geometric sum.\n\nIt boils down to:\n$$\\Large \\color{turquoise} h(k) - h(0) = \\sum\\limits_{t=1}^{k} \\color{orange} (-1)^t (n-1)^{t-1} \\color{turquoise} = \\sum\\limits_{t=1}^{k} \\color{orange} \\frac{(-1)^t (n-1)^t}{n-1}$$ (fancy way of multiplying by 1)\n\n$$\\Large \\color{turquoise} = \\color{orange} \\frac{1}{n-1} \\color{turquoise} \\sum\\limits_{t=1}^{k} \\color{orange} (-1)^t (n-1)^{t} \\color{turquoise} = \\color{orange} \\frac{1}{n-1} \\color{turquoise} \\sum\\limits_{t=1}^{k} \\color{orange} (1-n)^{t}$$\n\nand yeah I cannot be bothered to write out all the steps, but it\'s a simple application of the finite geometric sum formula.\n\nIn the end you get \n\n$$\\Large \\color{turquoise} h(k) = \\frac{(-1)^k (n-1)^k - 1}{n} + h(0)$$\n\nDefinition unravelling time! We know $\\large \\color{turquoise} h(k) = (-1)^k g(k) = (-1)^k f_k(i)$\n\n$$\\Large \\color{turquoise} (-1)^k f_k(i) = \\frac{(-1)^k (n-1)^k - 1}{n} + (-1)^0 f_0(i)$$\n\nResolving and simplifying all this yields\n\n$$\\Large \\color{magenta} f_k(i) = \\frac{(n-1)^k - (-1)^k}{n} + (-1)^k f_0(i)$$\n\nThat is really compact lmao. Anyway, this is the answer for a valid rotation state $\\color{pink} i$. The total answer will be the sum of this over all valid rotation states, then modulo $10^9 + 7$.\n\nFinding the valid indices is a matter of string matching. I hate string matching, so a good resource for the algo I used (Z) is https://codeforces.com/blog/entry/3107\n\n# Complexity\n- Time complexity:\n$$\\color{violet} O(n \\log(k))$$\n\n- Space complexity:\n $$\\color{violet} O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\nI used the Z-Algorithm over KMP because it sounds cooler.\n```\nclass Solution {\npublic:\n const int M = (int) 1e9 + 7;\n int z[(int) 2e6 + 5];\n void populateZ(string s){\n int n = s.size();\n int L = 0, R = 0;\n for (int i = 1; i < n; i++) {\n if (i > R) {\n L = R = i;\n while (R < n && s[R-L] == s[R]) R++;\n z[i] = R-L; R--;\n } else {\n int k = i-L;\n if (z[k] < R-i+1) z[i] = z[k];\n else {\n L = i;\n while (R < n && s[R-L] == s[R]) R++;\n z[i] = R-L; R--;\n }\n }\n }\n }\n\n long long binpow(long long a, long long b) {\n a %= M;\n long long res = 1;\n while (b > 0) {\n // this is really smart, its basically cycling through all binary digits and if there\'s a 1 there, multiply res by it!\n if (b & 1) // bit hacky way of checking b % 2 == 1\n res = (res * a) % M;\n a = (a * a) % M;\n b >>= 1;\n }\n return res % M;\n}\n\n int numberOfWays(string s, string t, long long k) {\n // g(k) = (n-1)^(k-1) - g(k-1)\n // g(1,0) = 3^0 - 1\n\n //\n\n // g(k,0) = g(k,1) + (-1)^k\n // g(k,1) = alternating sum of (n-1)^(k-1), just geo formula it\n\n // then summit (over all g(k,i) with i valid)\n\n // so find the valid i\'s\n\n // abcdabcd\n // 2\n\n \n string bruh = t+"$"+s+s; \n\n\n populateZ(bruh);\n int n = s.size();\n long long ans = 0;\n long long invN = binpow(n,M-2);\n for (int i = n+1; i < bruh.size(); ++i){\n if (i-n-1 >= n)\n break;\n if (z[i] == s.size()){\n ans += (binpow(n-1,k) - (k & 1 ? -1 : 1))*invN;\n if (i - s.size() - 1 == 0)\n ans += (k & 1 ? -1 : 1);\n }\n ans %= M;\n }\n\n return ans % M;\n \n }\n};\n``` | 8 | 0 | ['Math', 'Recursion', 'C++'] | 4 |
string-transformation | Python solution, O(n), string hash + combinatorics | python-solution-on-string-hash-combinato-6c9x | The question consists of two parts:\n\n1. String matching. Find all 0 < r < n, so that after an r-rotation from s, s is the same as t.\n2. Combinatorics. For an | Maruzensky | NORMAL | 2023-09-10T04:00:58.812543+00:00 | 2023-09-11T17:40:40.896595+00:00 | 979 | false | The question consists of two parts:\n\n1. String matching. Find all 0 < r < n, so that after an r-rotation from s, s is the same as t.\n2. Combinatorics. For an r in step 1, count the number of x_1, ..., x_k, so that for each x_i, 0 < x_i < n and x_1 + ... + x_k = r (mod n).\n\nFor part 1, we will do string hash. Basically it takes O(n) to compute a hash of a string and O(1) to update a string hash to the string hash of its 1-rotation.\n\nFor part 2, we can explain this by generating function.\n\nWe want to find x_1, ..., x_k, so that for each x_i, 0 < x_i < n and x_1 + ... + x_k = r (mod n).\n\nNow, let f(z) = z + z^2 + ... + z^(n - 1). Suppose z != 1 and z^n = 1.\nThen, we know that z^(an + r) = z^r.\n\nAnd. f(z)^k will be the number of combinations that we want.\n\nTo imagine about this, suppose x_1, ..., x_k satisfies the conditions.\nThen z^(x_1) shows up in the first copy of f(z)^k, z^(x_2) shows up in the second copy,..., and z^(x_k) shows up in the k-th copy.\nTherefore, (... + z^(x_1) + ...)(... + z^(x_2) + ...)(... + z^(x_k) + ...) contributes a z^r coefficient.\n\nHowever, if z != 1 and z^n = 1, since z^n - 1 = (z - 1)(z^(n-1) + ... + z + 1),\nf(z) = -1, and f(z) = (-1)^k.\n\nTherefore, let C(r, k) be the number of combinations x_1, ..., x_k, so that for each x_i, 0 < x_i < n and x_1 + ... + x_k = r (mod n),\nthen we will have\n\nC(0, k) - C(r, k) = (-1)^k, if r != 0.\n\nOn the other hand, we know that C(0, k) + ... + C(n - 1, k) = (n - 1)^k,\nso\n\nC(r, k) = ((n - 1)^k - (-1)^k) / n, if r != 0, and\nC(0, k) = C(r, k) + (-1)^k.\n\n```\nclass Solution:\n\n def numberOfWays(self, s: str, t: str, k: int) -> int:\n def power(p, x, e):\n """The O(log(e)) algorithm which returns x^e (mod p)"""\n base = x\n answer = 1\n while e:\n if e & 1:\n answer = (answer * base) % p\n\n base = (base * base) % p\n e >>= 1\n\n return answer\n\n def inv(p, x):\n """The O(log(p)) algorithm, given p and x,\n returns the mod p inverse, i.e., a value y such that x * y = 1 (mod p)"""\n return power(p, x, p - 2)\n\n P = 10 ** 9 + 7\n MOD = 2 ** 63 - 25\n INV = inv(MOD, 26)\n\n char_dict = {chr(ord(\'a\') + i): i for i in range(26)} # \'a\' -> 0, \'b\' -> 1, ..., \'z\' -> 25\n\n def new_hash(s):\n """Given a string s, returns a hash of s.\n We define the hash of s as (s[0] * 26^0 + s[1] * 26^1 + s[2] * 26^2 + ...) (mod MOD)"""\n answer = 0\n p = 1\n\n for c in s:\n answer = (answer + char_dict[c] * p) % MOD\n p = (p * 26) % MOD\n\n return answer\n\n ht = new_hash(t) # Get the hash of t\n good = [] # Stores all the desired rotation.\n\n n = len(s)\n SH = (1 - power(MOD, 26, n)) % MOD # SH = 1 - 26^n (mod MOD), see below.\n\n hs = new_hash(s) # The hash of unrotated s\n\n # Goal, for each i, compare the hash of rotate(s, i) and t.\n # If hashes are the same, (with high probability) they are the same.\n for i in range(n):\n if hs == ht:\n good.append(i)\n\n # Iteration. Given the previous hash hs, compute the next (right) rotated hs.\n\t\t\t# In this question, right rotation is equivalent to left rotation.\n # Intuition for this: As an example,\n # Non-rotated: abcd, hash = a * 26^0 + b * 26^1 + c * 26^2 + d * 26^3\n # Rotated: dabc, hash = a * 26^1 + b * 26^2 + c * 26^3 + d * 26^0\n # New hash = (Old hash) * 26 + d * (1 - 26^4)\n c = char_dict[s[n - 1 - i]]\n hs = (26 * hs + c * SH) % MOD\n\n if not good:\n return 0\n\n # The combinatoric problem: Given k, r\n # we want to find the number of x_1,..., x_k such that 0 < x_i < n for each x_i,\n # and x_1 + ... + x_k = r (mod n).\n # The answer would be the summation of all the r in good (number of rotations which make s = t)\n # Pleas refer to the article for more explanations.\n\n n_0 = 1 if good[0] == 0 else 0 # 1 if s == t; otherwise 0\n n_r = len(good) - n_0 # Number of valid nonzero shifts\n\n c_r_k = (power(P, n - 1, k) - (-1) ** k) * inv(P, n) # Number of combinations when r != 0\n c_0_k = c_r_k + (-1) ** k # Number of combinations when r = 0\n\n return (n_0 * c_0_k + n_r * c_r_k) % P\n``` | 8 | 0 | [] | 1 |
string-transformation | String Matching || Dynamic Programming || Matrix Exponential || C++ | string-matching-dynamic-programming-matr-94wi | \n# Approach\n- We can make string t from string s in minimum one step and if it doesn\'t then we can\'t make it to string t.\n- Let, move to the dp solution fo | Syphenlm12 | NORMAL | 2023-09-10T14:40:09.882184+00:00 | 2023-09-10T14:40:09.882214+00:00 | 802 | false | \n# Approach\n- We can make string t from string s in minimum one step and if it doesn\'t then we can\'t make it to string t.\n- Let, move to the dp solution for this question.\n- dp[1][i] represent that on the ith step we can our string to be equal to string t its number of ways to make it.\n- dp[0][i] represent that on the ith step we won\'t want to make our string to be equal to string t its number of ways.\n- And also if you notice we may make string t from string s from multiple indexes.\nex : s = "aaaa" and t = "aaaa"\nthe Possibilities are [0,n-1], [1,n-1]+[0,0], [2,n-1]+[0,1],...,and some more.\n- So basically we need to cnt the indexes from where my suffix + prefix become equals to t.\nNow comes to the transition.\n- Let c = count of indexes where suffix + prefix become equals to t.\n- dp[1][i] = dp[1][i-1] * (c - 1) + dp[0][i-1] * (c);\nhere what happens is,\n1. If on the ith step we want to make our string equals to t and on the previous step my string was t then their is c - 1 strings we have option to make.\n2. If on the ith step we want to make our string equals to t and on the previous step my string was not t then their is c strings we have option to make.\n- dp[0][i] = dp[1][i - 1] * (n-1-(c-1)) + dp[0][i-1] * (n-1-c);\nHere what happens is,\n1. If on the ith step we won\'t want to make our string equals to t and on the previous step my string was equal to t then their is n - 1 - (c - 1) strings we have option to make. c - 1 is substracted because already we made one string which is equals to t on the i - 1th step.\n2. If on the ith step we won\'t want to make our string equals to t and on the previous step my string was not equal to t then their is n - 1 - c strings we have option to make.\n- My answer will be dp[1][k].\n- But Here k is too large for the dp solution so here we use the concept of matrix exponential.\n- You can refer Youtube videos or any good blog for the understanding the matrix exponential.\nhttps://www.youtube.com/watch?v=eMXNWcbw75E\n\n# Complexity\n- Time complexity:\nO(n + log2(k) * (4 * 4 * 4))\n\n# Code\n```\nclass Hash {\nprivate:\n int n;\n long long p;\n long long mod;\n vector<long long> Hs;\n vector<long long> Ht;\n vector<long long> P;\npublic:\n Hash(int n, long long p, int mod) {\n this->n = n;\n this->p = p;\n this->mod = mod;\n Hs.resize(n + 1);\n Ht.resize(n + 1);\n P.resize(n + 1);\n }\n void build(string s, string t) {\n P[0] = 1;\n for(int i = 1; i <= n; i++) {\n P[i] = (P[i - 1] % mod * p % mod) % mod;\n Hs[i] = (Hs[i - 1] % mod + ((s[i - 1] - \'a\' + 1) % mod * 1LL * P[i] % mod) % mod) % mod; \n Ht[i] = (Ht[i - 1] % mod + ((t[i - 1] - \'a\' + 1) % mod * 1LL * P[i] % mod) % mod) % mod; \n }\n }\n bool isFine(int i) {\n long long h1 = ((Hs[n] - Hs[i] + mod) % mod + (Hs[i] % mod * P[n] % mod) % mod) % mod;\n long long h2 = (Ht[n] % mod * P[i] % mod) % mod;\n return (h1 == h2);\n }\n};\n\n\n\nclass Solution {\npublic:\n const int mod = 1e9 + 7;\n vector<vector<long long>> __init__ = {{1LL, 0LL}, {0, 1LL}};\n vector<vector<long long>> matrix_multiplication(vector<vector<long long>>& A, vector<vector<long long>>& B) {\n int n = A.size(), m = A[0].size(), x = B[0].size();\n vector<vector<long long>> ans(n, vector<long long>(x));\n for(int i = 0; i < n; i++) {\n for(int c = 0; c < x; c++) {\n for(int k = 0; k < m; k++) {\n ans[i][c] += (A[i][k] % mod * B[k][c] % mod);\n ans[i][c] %= mod;\n }\n }\n }\n return ans;\n }\n\n vector<vector<long long>> bin_pow(vector<vector<long long>> A, long long b) {\n vector<vector<long long>> result = __init__;\n while(b > 0) {\n if(b % 2 == 1) {\n result = matrix_multiplication(result, A);\n }\n A = matrix_multiplication(A, A);\n b /= 2;\n }\n return result;\n }\n \n int numberOfWays(string s, string t, long long k) {\n int n = (int) s.size();\n long long cnt = (s == t);\n Hash H1(n, 37LL, 1e9 + 9);\n Hash H2(n, 41LL, 1e9 + 21);\n H1.build(s, t);\n H2.build(s, t);\n for(int i = 1; i + 1 <= n; i++) {\n int fine = H1.isFine(i) & H2.isFine(i);\n cnt += fine;\n }\n vector<vector<long long>> matrix = {{cnt - 1, cnt}, {n - 1 - (cnt - 1), n - 1 - cnt}};\n matrix = bin_pow(matrix, k);\n long long ans = ((matrix[0][0] * (s == t)) + (matrix[0][1] * (s != t))) % mod;\n return ans;\n \n }\n};\n``` | 7 | 0 | ['Dynamic Programming', 'Rolling Hash', 'String Matching', 'Matrix', 'C++'] | 2 |
string-transformation | Complete guide covering all topics with links from where to study || Brute Force->optimal | complete-guide-covering-all-topics-with-q583b | Hey folks don't give up.IntuitionWe only have to return the number of ways in which s can be transformed into t in exactly k operations. Whenever such type of s | Ayush-Rawat | NORMAL | 2025-01-11T17:15:56.226268+00:00 | 2025-01-12T06:19:53.941256+00:00 | 625 | false | `Hey folks don't give up.`
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
We only have to return the number of ways in which s can be transformed into t in exactly k operations. Whenever such type of string question comes don't think of actually transforming the string.
Without transforming the string think how we can get to our answer.Don't think of time complexity right now.
Read the complete article.
# Approach
<!-- Describe your approach to solving the problem. -->
If k=0 then if s is equal to t then answer is 1 else its 0.(This is sort of base condition.)
Let good string be desired string and bad string be undesired string.
Let good count be the count of indexes from where if I rotate the string I get good string. (Each operation is just a rotation.)
Let bad count be the count of indexes from where if I rotate the string I get bad string.
Now to reach a good string i can come from another good string or from a bad string.
Now to reach a bad string i can come from another bad string or from a good string.
```
good ways after h moves be g(h)
bad ways after h moves be b(h)
good => count of good indices/rotation
bad => count of bad indices/rotation
g(h) => g(h-1)*(good-1) + b(h-1)*(good)
good to other good + bad to good
b(h) => g(h-1)*(bad) + b(h-1)*(bad-1)
good to bad + bad to other bad
```
After each move my string must be rotated.
**EXAMPLES:**
s=`"abcd"`, then these are the corresponding Rotated States:
- 0 -> abcd
- 1 -> dabc
- 2 -> cdab
- 3 -> bcda
# ***Good String***
1. If previous string was good then there are (good-1) ways to reach new good string. But Why? the reason is simple i cannot stay at same rotated state. And if i rotate my string then i can only change to other good states. I will explain it with example too.⬇️⬇️
2. If previous string was bad then there are good ways to reach new good string.
# ***Bad String***
1. If previous string was bad then there are (bad-1) ways to reach new bad string.
2. If previous string was good then there are bad ways to reach new bad string.
**Example**
- s = "ababab", t = "ababab"
- n = length of s = 6
- good string = t
- bad string = string those are not t like "bababa"
- here good count = 3
(as rotation from index 0,2,4 gives me good string that is t.)
- bad count = remaining index = n - good = 3
In short if we have data of previous state that is [good ways, bad ways] and we calculate [new good ways, new bad ways]
But what about the first state as there is no previous state for it.
Lets analyze, for first state that is k=0 (no operation performed)
my dp=[same, 1-same]. And same= (s == t). that is if (s==t) then same=1, else its zero.
**If s == t**
-
- dp= [1, 0]
- as there is only one way to get good string without performing any operation
**If s != t**
-
- dp= [0, 1]
- as there is no way to get good string without performing any operation
`Hey folks don't give up.`
# String Matching
If s is rotation of t then only we can convert s to t else my answer is *zero*. And this can be find by finding occurence of t in s+s.
To understand it better you can solve https://leetcode.com/problems/rotate-string/
And we can also find indexes too. Any string matching algorithm like kmp,z algorith, rolling hash(rabin karp) can be used. We have just apply it once. It gives me count of occurence. And this is my good count.
https://www.geeksforgeeks.org/kmp-algorithm-for-pattern-searching/
I am using kmp here you can use other algorithms too.
```python3 []
def kmp():
count=0
lps=[0]*n
i,j=1,0
while i < n:
if t[i] == t[j]:
j+=1
lps[i]=j
i+=1
elif j > 0:
j=lps[j-1]
else:
i+=1
i,j=0,0
while i < len(x):
if x[i] == t[j]:
j+=1
i+=1
elif j > 0:
j=lps[j-1]
else:
i+=1
if j == n:
count+=1
j=lps[j-1]
return count
```
# Dynamic Programming
I have already explained the dp approach. And in constant space and linear time we can find total good ways after exactly K moves.
```python3 []
def dp_sol1():
# give tle as k is too large
dp=[same,1-same] # [good ways, bad ways]
# after each move i have to rotate (can't stay on same)rotation
for _ in range(k):
newdp=[0,0]
newdp[0]=(dp[0]*(good-1) + dp[1]*(good))%MOD
# good to other goods + bad to good
newdp[1]=(dp[0]*(bad) + dp[1]*(bad-1)) %MOD
# good to bad + bad to other bads
dp=newdp
return dp[0] # return total good ways
```
# Approach 1 Code
Gives ***TLE*** but `important to understand`
```python3 []
class Solution:
def numberOfWays(self, s: str, t: str, k: int) -> int:
n=len(t)
x=s+s[:n-1]
MOD=10**9+7
def kmp():
count=0
lps=[0]*n
i,j=1,0
while i < n:
if t[i] == t[j]:
j+=1
lps[i]=j
i+=1
elif j > 0:
j=lps[j-1]
else:
i+=1
i,j=0,0
while i < len(x):
if x[i] == t[j]:
j+=1
i+=1
elif j > 0:
j=lps[j-1]
else:
i+=1
if j == n:
count+=1
j=lps[j-1]
return count
good=kmp()
bad,same=n-good,int(s == t)
if good == 0:
return 0
dp=[same,1-same] # [good ways, bad ways]
# after each move i have to rotate cant stay on same rotation
for _ in range(k):
newdp=[0,0]
newdp[0]=(dp[0]*(good-1) + dp[1]*(good))%MOD
# good to other goods + bad to good
newdp[1]=(dp[0]*(bad) + dp[1]*(bad-1)) %MOD
# good to bad + bad to other bads
dp=newdp
return dp[0]
```
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
$$O(k)$$
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
$$O(1)$$
# Why TLE
So the main problem here is K is too large. `1 <= k <= 10^15`
And the good part is we have solved it in constant space.
So this is a standard problem where we have dp of linear time constant space we can solve it in d³log(n).
Here comes Matrix Exponentiation in play.
`Hey folks don't give up.`
# Matrix Exponentiation
I recommend you to watch some good tutorial for this topic.
[You can watch this video](https://youtu.be/eMXNWcbw75E?si=itXnDIr3-3NHs-85)
I highky recommend you to go through this article once https://zobayer.blogspot.com/2010/11/matrix-exponentiation.html
I believe you have gone through the tutorial and article.

From the above image let mat = matrix, prev= previous state, new = new state
first_state=[[same],[1-same]], And to quickly get result after n operation we will use matrix exponentaion.
new state / desired state = matⁿ * first_state
Don't get confused by n it just denote the number of operation.
And this caclutation only takes 2³log(n) time.
*Please upvote.*
# Code
```python3 []
'''
good ways after h moves be g(h)
bad ways after h moves be b(h)
good => count of good indices/rotation
bad => count of bad indices/rotation
g(h) => g(h-1)*(good-1) + b(h-1)*(good)
good to other good + bad to good
b(h) => g(h-1)*(bad) + b(h-1)*(bad-1)
good to bad + bad to other bad
matrix X prev_states ==> new_states
| good-1 good | X | g(h-1) | ==> | g(h) |
| bad bad-1 | | b(h-1) | | b(h) |
'''
class Solution:
def numberOfWays(self, s: str, t: str, k: int) -> int:
n=len(t)
x=s+s[:n-1]
MOD=10**9+7
def kmp():
count=0
lps=[0]*n
i,j=1,0
while i < n:
if t[i] == t[j]:
j+=1
lps[i]=j
i+=1
elif j > 0:
j=lps[j-1]
else:
i+=1
i,j=0,0
while i < len(x):
if x[i] == t[j]:
j+=1
i+=1
elif j > 0:
j=lps[j-1]
else:
i+=1
if j == n:
count+=1
j=lps[j-1]
return count
good=kmp()
bad,same=n-good,int(s == t)
if good == 0:
return 0
def dp_sol1():
# give tle as k is too large
dp=[same,1-same] # [good ways, bad ways]
# after each move i have to rotate cant stay on same rotation
for _ in range(k):
newdp=[0,0]
newdp[0]=(dp[0]*(good-1) + dp[1]*(good))%MOD
# good to other goods + bad to good
newdp[1]=(dp[0]*(bad) + dp[1]*(bad-1)) %MOD
# good to bad + bad to other bads
dp=newdp
return dp[0]
dp=[[same],[1-same]]
def multiply(a,b):
x,y,z=len(a),len(a[0]),len(b[0])
product=[[0]*z for _ in range(x)]
for i in range(x):
for j in range(z):
for k in range(y):
product[i][j] += a[i][k]*b[k][j]
product[i][j] %= MOD
return product
def exp_power(mat,p):
res=[[1,0],[0,1]]
while p>0:
if p%2 == 1:
res=multiply(res,mat)
mat=multiply(mat,mat)
p//=2
return res
mat=[[good-1,good],[bad,bad-1]]
mat=exp_power(mat,k)
dp=multiply(mat,dp)
return dp[0][0]
```
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
$$O(n + log(k))$$
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
$$O(1)$$ | 6 | 0 | ['Math', 'String', 'Dynamic Programming', 'Recursion', 'String Matching', 'Matrix', 'Java', 'Python3'] | 0 |
string-transformation | ✅ [Python] Short and Explained || 100% Faster || Sum of Geometric Series | python-short-and-explained-100-faster-su-iz5w | Please UPVOTE if you LIKE! \uD83D\uDE01\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \n r denotes the number of times that string | linfq | NORMAL | 2023-11-06T08:40:29.789086+00:00 | 2023-11-06T08:47:41.142788+00:00 | 714 | false | **Please UPVOTE if you LIKE!** \uD83D\uDE01\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n* r denotes the number of times that string s obtains itself through rotation 0 <= l < n. Obviously r is at least 1, when l == 0.\n\n - It means if s can be transformed into t and s != t, then there are r ways to transform s into t in one step.\n - However, if s==t, then there are only r-1 ways\n - Notice that r also equals to the number of times that string t obtains itself through rotation 0 <= l < n\n\n\n \n* For given s and t, we simplify numberOfWays(self, s, t, k) to f(k)\n* We consider the recursive formula of f(k). We note that s is transformed into s\' after k-1 transformations. There are no more than two situations, s\' != t and s\' == t.\n* f(k-1) is the number of ways that s is transformed into t after k-1 transformations. \n* $$f(k-1) * (r-1)$$ denotes that after k-1 transformations s is transformed into t, then we have r-1 ways to transform t to t itself.\n* 0 < l < n, so for each time, we have n-1 possible choices, then for k-1 transformations, we totally have $$(n-1)^{k-1}$$ possible choices.\n* $$ [(n - 1)^{k-1} - f(k - 1)] * r $$ denotes that after k-1 transformations s is not transformed into t, then we have r different ways to transform s\' into t.\n* Finally, we have $$ f(k) = f(k-1) * (r-1) + [(n - 1)^{k-1} - f(k - 1)] * r = (n - 1)^{k - 1} * r - f(k - 1)$$\n \n - $$f(k) + f(k-1) = (n -1)^{k-1} * r$$\n* Because the maximum k is $$10^{15}$$, we cannot solve it step by step recursively. We continue to derive the formula.\n* It is easy to get $$f(k-1) + f(k-2) = (n -1)^{k-2} * r$$, so $$ f(k) - f(k-2) = (n-2)*(n-1)^{k-2}*r$$\n* It is easy to get that $$f(0) = (s == t)$$ and $$ f(1) = r - f(0)$$\n* If k % 2 == 0, then $$ f(k) - f(0) = [f(k) - f(k - 2)] + [f(k -2) - f(k - 4)] +...+ [f(4) - f(2)]+ [f(2) - f(0)]$$\n\n - $$[f(2)\u2212f(0)], ..., [f(k)\u2212f(k\u22122)]$$ is a geometric series\n - $$ q = \\frac{f(k)\u2212f(k\u22122)}{f(k-2)\u2212f(k\u22124)} = (n-1)^2$$\n - $$ a_1 = f(2)\u2212f(0) = (n - 2) * r $$\n - the length of the geometric series is k // 2\n - so we can use the geometric series summation formula $$Sn=a_1(1-q^n)/(1-q)\uFF08q\u22601) $$ to calculate $$ f(k) - f(0)$$, then we can get $$f(k) = Sn + f(0) $$\n* If k % 2 == 1, then $$ f(k) - f(1) = [f(k) - f(k - 2)] + [f(k -2) - f(k - 4)] +...+ [f(5) - f(3)]+ [f(3) - f(1)]$$\n \n - $$[f(3)\u2212f(1)], ..., [f(k)\u2212f(k\u22122)]$$ is a geometric series\n - $$ q = \\frac{f(k)\u2212f(k\u22122)}{f(k-2)\u2212f(k\u22124)} = (n-1)^2$$\n - $$ a_1 = f(3)\u2212f(1) = (n - 2) * (n - 1) * r $$\n - the length of the geometric series is k // 2\n - so we can use the geometric series summation formula $$Sn=a_1(1-q^n)/(1-q)\uFF08q\u22601) $$ to calculate $$ f(k) - f(1)$$, then we can get $$f(k) = Sn + f(1) $$\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(N)$$ with python build-in string find function\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n$$O(N)$$\n# Code\n```\nclass Solution(object):\n def numberOfWays(self, s, t, k):\n """\n :type s: str\n :type t: str\n :type k: int\n :rtype: int\n """\n ss = s + s\n if t not in ss: # s cannot be transformed into t\n return 0\n\n mod = 10 ** 9 + 7\n n = len(s)\n f0 = int(s == t)\n r = n // ss.find(s, 1)\n f1 = r - f0\n left = f0 if k % 2 == 0 else f1\n\n a1 = (n - 2) * r if k % 2 == 0 else (n - 2) * (n - 1) * r\n q = (n - 1) ** 2\n if q == 1:\n ans = (a1 * (k // 2) + left) % mod\n else:\n ans = a1 * (pow(q, k // 2, mod * (q - 1)) - 1) / (q - 1) + left\n\n return ans % mod\n```\n\n**If you have any question, feel free to ask. If you like the solution or the explanation, Please UPVOTE!** | 6 | 0 | ['Python', 'Python3'] | 0 |
string-transformation | I got KMP and matrix multiply code from ChatGPT.. | i-got-kmp-and-matrix-multiply-code-from-vnnb6 | Intuition\nYou can see it\'s DP, and need KMP and matrix multiply to improve performace.\n\nWhen coding the solution, I got KMP and matrix multiply code from Ch | suiyuan1992 | NORMAL | 2023-09-10T04:16:33.071570+00:00 | 2023-09-10T04:16:33.071589+00:00 | 1,272 | false | # Intuition\nYou can see it\'s DP, and need KMP and matrix multiply to improve performace.\n\nWhen coding the solution, I got KMP and matrix multiply code from ChatGPT..\n\n# Code\n```\nclass Solution {\nprivate:\nstd::vector<int> buildKMPTable(const std::string& pattern) {\n int m = pattern.length();\n std::vector<int> table(m, 0);\n int len = 0;\n int i = 1;\n\n while (i < m) {\n if (pattern[i] == pattern[len]) {\n len++;\n table[i] = len;\n i++;\n } else {\n if (len != 0) {\n len = table[len - 1];\n } else {\n table[i] = 0;\n i++;\n }\n }\n }\n return table;\n}\n\nint countOccurrences(const std::string s, const std::string t) {\n int n = s.length();\n int m = t.length();\n if (m == 0) return 0;\n\n std::vector<int> table = buildKMPTable(t);\n int i = 0, j = 0;\n int count = 0;\n\n while (i < n) {\n if (s[i] == t[j]) {\n i++;\n j++;\n }\n\n if (j == m) {\n count++;\n j = table[j - 1];\n } else if (i < n && s[i] != t[j]) {\n if (j != 0) {\n j = table[j - 1];\n } else {\n i++;\n }\n }\n }\n return count;\n}\n \ntypedef vector<vector<long long>> Matrix;\nconst long long MOD = 1000000007;\n\n// \u77E9\u9635\u4E58\u6CD5\nMatrix multiply(const Matrix &a, const Matrix &b) {\n int n = a.size();\n int m = a[0].size();\n int p = b[0].size();\n Matrix c(n, vector<long long>(p, 0));\n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < p; ++j) {\n for (int k = 0; k < m; ++k) {\n c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % MOD;\n }\n }\n }\n return c;\n}\n\n// \u77E9\u9635\u5FEB\u901F\u5E42\nMatrix matrix_pow(Matrix base, long long n) {\n int sz = base.size();\n // \u521D\u59CB\u5316\u5355\u4F4D\u77E9\u9635\n Matrix res(sz, vector<long long>(sz, 0));\n for (int i = 0; i < sz; ++i) {\n res[i][i] = 1;\n }\n\n // \u5FEB\u901F\u5E42\u8BA1\u7B97\n while (n > 0) {\n if (n & 1) {\n res = multiply(res, base);\n }\n base = multiply(base, base);\n n >>= 1;\n }\n return res;\n}\npublic:\n int numberOfWays(string s, string t, long long k) {\n // f[i][0] = f[i-1][0] * (sz-1-same) + f[i-1][1] * (sz-1-same+1);\n // f[i][1] = f[i-1][0] * (same) + f[i-1][1] * (same-1);\n bool sign = (s==t);\n int sz = s.size();\n for(int i = 0;i<sz-1;i++)s+=s[i];\n int cnt = countOccurrences(s, t);\n if(cnt==0)return 0;\n Matrix base = {{sz-1-cnt, sz-cnt}, {cnt, cnt-1}};\n Matrix tt = matrix_pow(base, k);\n Matrix ans = {{1-sign}, {sign}};\n Matrix ret = multiply(tt, ans);\n return ret[1][0];\n }\n};\n``` | 5 | 0 | ['C++'] | 1 |
string-transformation | [C++] Using string::find is (in fact NOT) efficient enough | c-using-stringfind-is-in-fact-not-effici-n8d5 | [EDIT] Thanks to @lyronly, string::find costs O(N^2) and will not make it if extreme testcases are provided, such as:\n\ns="a"*499999+"b"\nt="a"*500000\n\n\n--- | orthogonal1 | NORMAL | 2023-09-10T10:02:15.373775+00:00 | 2023-09-11T08:58:23.105235+00:00 | 367 | false | [EDIT] Thanks to @lyronly, string::find costs O(N^2) and will not make it if extreme testcases are provided, such as:\n```\ns="a"*499999+"b"\nt="a"*500000\n```\n\n------------------\n\nI\'m surprised that string::find is efficient enough but there\'s no solutions posted here using it so far. I won\'t explain the math things here. \n\nps. Sorry for my poor English. (Why did I use "sufficient" when I was supposed to use "efficient"...)\n\n# Intuition\nThis problem is about finding the ways to rotate ```s``` to make it ```t``` and then do the math. \n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe most simple way to find if we can rotate ```s``` to make it ```t``` is to find whether ```s+s``` contains ```t```. This explains the first 3 lines in the code below.\nHowever, in this problem we want to know all the ways to rotate ```s``` to make it ```t```. Thus if we find one ```t``` in ```ss```, we want to check if another one exists and find its position. This part is done by the line of code:\n```\nauto found2=ss.find(t, found1+1);\n```\nThe second parameter means that we find the string from index ```found1+1```, hence guarantees that we don\'t find the same position.\nHere\'s the trick: If ```found2!=npos```, then ```s``` is in fact a string of period ```found2-found1```. Hence there\'s no need for another find as we have been able to conclude all the ways to rotate ```s``` to make it ```t```.\n\n# Code\n```\nlong long power_mod(long long a, long long b, int q){\n if(b<2){\n if(b==1) return a%q;\n return 1;\n }\n long long temp=power_mod(a, b/2, q);\n if(b%2==0) return temp*temp%q;\n return temp*temp%q*a%q;\n}\nconst int p=1e9+7;\n\nclass Solution {\npublic:\n int numberOfWays(string s, string t, long long k) {\n string ss=s+s;\n auto found1=ss.find(t);\n if(found1==std::string::npos) return 0;\n long long base=power_mod(s.size()-1, k, p);\n int diff=k%2==0? 1 : -1;\n base=(base-diff)*power_mod(s.size(), p-2, p)%p;\n auto found2=ss.find(t, found1+1);\n if(found2==std::string::npos){\n return base;\n }\n else if(found2-found1==s.size()){ //s=t\u4E14\u7121\u9031\u671F\n return (base+diff)%p;\n }\n else{\n int d=found2-found1;\n int ans_diff=found1==0? diff : 0;\n return (s.size()/d*base+ans_diff)%p;\n }\n }\n};\n``` | 4 | 0 | ['C++'] | 2 |
string-transformation | [Java] 37ms Math solution without DP | java-37ms-math-solution-without-dp-by-wd-i82s | Intuition\n\nThe solution is kinda cheating a little bit. But nevertheless, it is insane to have such a hard question in Leetcode. \n\nIdea: \n\nThe quesiton ba | wddd | NORMAL | 2023-09-10T06:10:15.232519+00:00 | 2024-05-30T01:37:43.540398+00:00 | 998 | false | # Intuition\n\nThe solution is kinda cheating a little bit. But nevertheless, it is insane to have such a hard question in Leetcode. \n\nIdea: \n\nThe quesiton basically asks \n1. After `k` times of rotation (each rotation takes `l (0 < l < n)` step), the counts of each unique ending strings. \n1. Then sum the total counts if the ending string equals to `t`.\n\nFirstly we need to know what unique ending string equals to `t`. That can be solved by standard rolling hash algorithm or z-algorithm.\n\nThe key question is to calculate the counts of them after `k` rotations. How to do that if you don\'t know DP or matrix multiplication?\n\nUse `s = "abcd", t = "cdab"` as an example. Let\'s rotate `abcd`:\n\n```\n| Counts of ending string | abcd | bcda | cdab | dabc |\n|-------------------------|------|------|------|------|\n| Rotation 1 | 0 | 1 | 1 | 1 |\n| Rotation 2 | 3 | 2 | 2 | 2 |\n| Rotation 3 | 6 | 7 | 7 | 7 |\n| Rotation 4 | 21 | 20 | 20 | 20 |\n```\n\nIt appears, counts of `bcda` `cdab` `dabc` are the same, and they are diff by 1 with `abcd` depends on `rotations % 2`. As long as we know how to calculate the counts of `abcd`, we will be able solve the problem.\n\nJust search `0 3 6 21` on OEIS, the first sequence (A054878) is what we need.\n\nhttps://oeis.org/search?q=0%2C3%2C6%2C21&language=english&go=Search\n\nIts fomula is $$a(n) = (3^n + (-1)^n*3)/4$$ for string of length 4, pretty easy to generalize it to string with arbitrary length.\n\n# Code \n\nBelow rolling hash solution didn\'t work because of the hash collision. Check the Z algorithm version.\n\n```\nimport java.math.BigInteger;\n\nclass Solution {\n public int numberOfWays(String s, String t, long k) {\n long[] hashS = initialHash(s);\n long hashT = initialHash(t)[0];\n\n int moves = 0;\n long nextHashS = hashS[0];\n for (int i = 0; i < s.length() - 1; i++) {\n nextHashS = nextHash(nextHashS, hashS[1], s.charAt(i), s.charAt(i));\n if (nextHashS == hashT) {\n moves++;\n }\n }\n\n if (moves == 0 && hashS[0] != hashT) {\n return 0;\n }\n\n BigInteger mod = BigInteger.valueOf((long) (1e9 + 7));\n BigInteger a = BigInteger.valueOf(s.length() - 1)\n .modPow(BigInteger.valueOf(k), mod)\n .add(BigInteger.valueOf(k % 2 == 0 ? s.length() - 1 : 1 - s.length()))\n .multiply(BigInteger.valueOf(s.length()).modInverse(mod))\n .mod(mod);\n\n BigInteger b = a.add(BigInteger.valueOf(k % 2 == 0 ? -1 : 1));\n\n BigInteger total = hashS[0] == hashT ? a : BigInteger.ZERO;\n total = total.add(b.multiply(BigInteger.valueOf(moves)));\n\n return total.mod(mod).intValue();\n }\n\n private long[] initialHash(String s) {\n long hash = 0;\n long pow = 1;\n\n for(int i = s.length() - 1; i >= 0; i--){\n hash += s.charAt(i) * pow;\n if (i > 0) {\n pow *= 37;\n }\n }\n\n return new long[] {hash, pow};\n }\n\n private long nextHash(long hash, long pow, char left, char right) {\n return (hash - left * pow) * 37 + right;\n }\n}\n```\n\nZ algorithm:\n\n```\nimport java.math.BigInteger;\n\nclass Solution {\n public int numberOfWays(String s, String t, long k) {\n int[] z = zFunction(s, t);\n\n int moves = 0;\n for (int i = s.length() + 1; i < s.length() * 2; i++) {\n if (z[i] >= s.length()) {\n moves++;\n }\n }\n\n if (moves == 0 && z[s.length()] < s.length()) {\n return 0;\n }\n\n BigInteger mod = BigInteger.valueOf((long) (1e9 + 7));\n BigInteger a = BigInteger.valueOf(s.length() - 1)\n .modPow(BigInteger.valueOf(k), mod)\n .add(BigInteger.valueOf(k % 2 == 0 ? s.length() - 1 : 1 - s.length()))\n .multiply(BigInteger.valueOf(s.length()).modInverse(mod))\n .mod(mod);\n\n BigInteger b = a.add(BigInteger.valueOf(k % 2 == 0 ? -1 : 1));\n\n BigInteger total = z[s.length()] >= s.length() ? a : BigInteger.ZERO;\n total = total.add(b.multiply(BigInteger.valueOf(moves)));\n\n return total.mod(mod).intValue();\n }\n\n private int[] zFunction(String s, String t) {\n int len = s.length();\n\n s = t + s + s;\n\n int[] z = new int[len * 3];\n\n int left = 0;\n int right = 0;\n for (int i = 1; i < len * 2; i++) {\n if (i < right) {\n z[i] = Math.min(right - i, z[i - left]);\n }\n while (i + z[i] < s.length() && s.charAt(i + z[i]) == s.charAt(z[i])) {\n z[i]++;\n }\n if (i + z[i] > right) {\n left = i;\n right = i + z[i];\n }\n }\n\n return z;\n }\n}\n```\n | 3 | 0 | ['Math', 'Rolling Hash', 'Java'] | 3 |
string-transformation | Three Steps: string match, recursion and speed up | three-steps-string-match-recursion-and-s-eapu | To solve this problem, you need to know:\n1 O(n) string match algorithm (I use z function as an example here):\nhttps://cp-algorithms.com/string/z-function.html | gaoyf1235 | NORMAL | 2023-09-10T05:17:43.829716+00:00 | 2023-09-10T05:47:17.513483+00:00 | 788 | false | To solve this problem, you need to know:\n1 O(n) string match algorithm (I use z function as an example here):\nhttps://cp-algorithms.com/string/z-function.html\n2 Fast modular inverse algorithm:\nhttps://cp-algorithms.com/algebra/binary-exp.html\nhttps://cp-algorithms.com/algebra/module-inverse.html\n\nThen the three steps:\n1 String match: The operation is just treat the string as a cyclic one, we can represent the string status with first character index. If we only consider the last step, it means to move it to a match position. This match position can be calculated by an O(n) string match algorithm, by find "s" in "t + t" (cyclic match check).\n\n2 Recursion: When we know the count of match positions:\n* The total move count is (n - 1) ^(k) at step k, equals to the macth move plus mismatch ones.\n* **match(k+1) = match_position_count * total_move_count(k) - match(k);**\n* Why? To make k+1 step match, we can move from any k step status to a match position, **except from an already matched position to itself**.\n* Now we have a O(N + K) solution, but K could be a large number!\n\n3 Speed up: math helps here:\n* match(k+1) = match_position_count * total_move_count(k) - match(k)\n\t\t\t\t\t = match_position_count * (n - 1) ^ k - match(k)\n\t\t\t\t\t = match_position_count * (n - 1) ^ k) - ( match_position_count * total_move_count(k-1) - match(k-1))\n\t\t\t\t\t = match_position_count * (n - 1) ^ k - (match_position_count * (n - 1) ^(k - 1) - match(k - 1))\n\t\t\t\t\t = match_position_count * ( (n - 1) ^ k) - (n - 1) ^(k - 1) + (n - 1) ^(k - 2) - .. (n - 1) * (-1)^ k ) + (-1)^(k+1) * match(1);\n\t\t\t\t\t = match_position_count * ((n - 1) ^(k + 1) + (-1)^ k * (n - 1)) / n + (-1)^(k+1) * match(1);\nhttps://en.wikipedia.org/wiki/Geometric_progression\n\n* Then we calculate the final results with fast binary exponentiation for (n - 1) ^(k + 1)\n* To divide by n, use modular inverse algorithnm.\n* The O(N + logK) solution done!\n\n\n\n\n\n```\nclass Solution {\n using ll = long long;\n ll mod = 1e9 + 7;\n vector<int> z_function(string& s) {\n int n = (int) s.length();\n vector<int> z(n);\n for (int i = 1, l = 0, r = 0; i < n; i++) {\n // [l, r] is checked, reuse this info => z[i] = z[i - l], but bounded by r -i + 1\n if (i <= r) z[i] = min (r - i + 1, z[i - l]);\n // Single char match check\n while (i + z[i] < n && s[z[i]] == s[i + z[i]]) z[i]++;\n // Update r[i] if we get a larger z box\n if (i + z[i] - 1 > r){\n l = i;\n r = i + z[i] - 1;\n }\n }\n return z;\n }\n \n ll modExp(ll x, ll y){\n if(y == 0) return 1;\n ll half_exp = modExp(x, y / 2);\n if(y % 2 == 0) return (half_exp * half_exp) % mod;\n else return (((half_exp * half_exp) % mod) * x) % mod;\n }\npublic:\n int numberOfWays(string s, string t, long long k) {\n int n = t.size();\n string temp = t + t;\n string comb = s + "$" + temp;\n vector<int> zf = z_function(comb);\n vector<int> shifts;\n int has_zero = 0;\n for(int i = n + 1; i < zf.size(); i++){\n int shift = i - n - 1;\n if(zf[i] == n && shift < n) {\n if(shift == 0) has_zero = 1;\n shifts.push_back(i - n - 1);\n }\n }\n if(shifts.empty()) return 0;\n if(k == 1) return shifts.size() - has_zero;\n ll base = n - 1;\n ll base_plus_one_inv = modExp(base + 1, mod - 2);\n ll r1 = shifts.size() - has_zero;\n ll c = shifts.size();\n ll res = 0;\n if(k % 2 == 0){\n res = ((c * (modExp(base, k) + base) % mod) * base_plus_one_inv + mod - r1) % mod;\n }\n else{\n res = ((c * (modExp(base, k) + mod - base) % mod) * base_plus_one_inv + r1) % mod;\n }\n return res; \n }\n};\n``` | 3 | 0 | ['C'] | 0 |
string-transformation | [Python] Cheating with built-in find | python-cheating-with-built-in-find-by-re-e4vt | Finish this solution after the contest. :( \nCheating on some special cases. Using find is enough.\nres represents the number of ways by rotating s to get it se | Remineva | NORMAL | 2023-09-10T04:40:01.978320+00:00 | 2023-09-12T20:25:20.264282+00:00 | 1,722 | false | Finish this solution after the contest. :( \nCheating on some special cases. Using `find` is enough.\n`res` represents the number of ways by rotating `s` to get it self. Let `f_k` be the solution for `k` operations. Then we have `f_{k+1} = [(n-1)^k - f_k] * res + f_k * (res - 1)`, which gives us `f_k = (-1)^k * (f_0 - res/n) + (n - 1)^k * res / n`, where `f_0 = s == t`.\n```\nclass Solution:\n def numberOfWays(self, s: str, t: str, k: int) -> int:\n M = 10 ** 9 + 7\n cnt = Counter(s)\n n = len(s)\n i = (s + s).find(t)\n if i == -1:\n return 0\n if len(cnt) == 1:\n return pow(n - 1, k, M) % M\n elif len(cnt) == 2:\n if s == s[:2] * (n // 2):\n res = n // 2\n if s == t:\n curr = pow(n - 1, k, M) * res\n if k & 1:\n curr -= n - res\n else:\n curr += n - res\n return curr * pow(n, -1, M) % M\n else:\n curr = pow(n - 1, k, M) * res\n if k & 1:\n curr += res\n else:\n curr -= res\n return curr * pow(n, -1, M) % M\n \n\n\n ss = s[i+1:] + s\n res = 1\n while len(ss) > n:\n i = ss.find(t)\n if i == -1:\n break\n if i <= len(ss) - n - 1:\n res += 1\n ss = ss[i+1:]\n \n if s == t:\n curr = pow(n - 1, k, M) * res\n if k & 1:\n curr -= n - res\n else:\n curr += n - res\n return curr * pow(n, -1, M) % M\n else:\n curr = pow(n - 1, k, M) * res\n if k & 1:\n curr += res\n else:\n curr -= res\n return curr * pow(n, -1, M) % M\n``` | 3 | 0 | ['Python'] | 1 |
string-transformation | [Python] - linear algebra + KMP O(log(k)+n) | python-linear-algebra-kmp-ologkn-by-knat-kpg0 | Sorry for my bad handwriting >.<\n\n\n\n\n\n\n\n\n\n# Code\n\nclass Solution:\n def compute_lps_array(self, pattern):\n length = 0\n lps = [0] | knatti | NORMAL | 2024-01-31T13:51:08.263483+00:00 | 2024-02-07T08:29:56.925779+00:00 | 473 | false | **Sorry for my bad handwriting >.<**\n\n\n\n\n\n\n\n\n\n# Code\n```\nclass Solution:\n def compute_lps_array(self, pattern):\n length = 0\n lps = [0] * len(pattern)\n i = 1\n\n while i < len(pattern):\n if pattern[i] == pattern[length]:\n length += 1\n lps[i] = length\n i += 1\n else:\n if length != 0:\n length = lps[length - 1]\n else:\n lps[i] = 0\n i += 1\n return lps\n\n def KMP_search(self, text, pattern):\n m = len(pattern)\n n = len(text)\n lps = self.compute_lps_array(pattern)\n cnt = 0\n i = j = 0\n while i < n:\n if pattern[j] == text[i]:\n i += 1\n j += 1\n\n if j == m:\n cnt += 1\n j = lps[j - 1]\n elif i < n and pattern[j] != text[i]:\n if j != 0:\n j = lps[j - 1]\n else:\n i += 1\n return cnt\n\n def numberOfWays(self, A: str, B: str, k: int) -> int:\n MOD = 10**9 + 7\n ka, kb = A == B, self.KMP_search(A[1:] + A[:-1], B)\n n = len(A)\n f = (pow(n - 1, k, MOD) - pow(-1, k)) * pow(n, MOD - 2, MOD)\n return ((ka+kb)*f+ka*pow(-1,k))%MOD\n```\n\n**For further practice, try using the same technique to derive a closed form-solution for the nth fibonacci number \uD83D\uDE01**\n\n### EDIT: \nThe function is the same as the one I derived in the first solution but we can do better on finding transfigurations.\n\nIn the first approach, I counted every transfiguration which isn\'t necessary.\n\ni.g.: abcabc has shifts `bcabca cabcab abcabc bcabca cabcab`\n\nonce we find the initial permutation in the shifts, the pattern repeats. In the implementation below I only use string searching until I find the index of the initial permutation, calculate the cycle length and then I know exactly how many occurences there are of each transfiguration indicated by ka, kb \uD83D\uDE01\n\n### Code\n\n```python\nMOD = 10**9 + 7\nclass Solution:\n def numberOfWays(self, A: str, B: str, k: int) -> int:\n if (2 * A).find(B) == -1: return 0\n n = len(A)\n ka, kb = A == B, n // (2 * A).find(A, 1) - (A == B)\n f = (pow(n - 1, k, MOD) - pow(-1, k)) * pow(n, MOD - 2, MOD)\n return ((ka + kb) * f + ka * pow(-1, k)) % MOD\n``` | 2 | 0 | ['Python3'] | 1 |
string-transformation | eh | eh-by-user3043sb-fhyv | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | user3043SB | NORMAL | 2024-01-23T13:49:41.792294+00:00 | 2024-01-23T13:49:41.792340+00:00 | 177 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nimport java.util.*;\n\nclass Solution {\n\n // basically adding suffix at the start == string rotation when K = 1 == same as rotating prefix at the end\n // so with K = 1 there are (N-1) possible rotations (results)\n\n\n // X\n // abcdabcd START k = 2 ways = 2\n // cdab GOAL\n\n // X\n // abababababab START k = 1 ways = 2\n // ababab 0\n // ababab 2\n // ababab 4\n // ababab 6\n\n // IDEA: transform the problem into: find T as substring in S+S !!!!\n // any rotation has cost = 1 but we want cost K !!!\n // so all matches of T in S+S are valid END STATES and want to sum the ways to get to each of them using K rotations\n // start -> any rotation cost = 1\n // start -> interim -> any rotation cost = 2\n\n // abcdabcd start ways to each "cdab" with cost=2\n // bcda 1 cost=1 start -> bcda -> cdab\n // cdab 2 cost=1 start -> dabc -> cdab\n // dabc 3 cost=1\n\n // Finally use KMP to find all matches of T in S+S and sum the ways of achieving each !!!\n\n //////////// BUT\n // abcdabcd start ways to each "cdab" with cost=2\n // bcda 1 p=1 start -> bcda -> cdab p=2 so 1+1\n // cdab 2 p=2 start -> dabc -> cdab p=2 so 3-1\n // dabc 3 p=3\n\n // K is too big, can\'t loop over it !!!! Optimise it out of the DP transition !!!!\n // Even O(N*K) which is the best we can do with this approach is too slow!!!! K is too big !!\n // Reformulate the idea !!!!!!!!! The way we were thinking was:\n // each substring ending at i can be shifted into a substring ending at j with cost = k = 1\n // this FORCES US TO go over Ks 1 by 1 ..... and K is TOO BIG !!!\n // instead of using K=1 for 1 step = shift of P to the left/right, use Q itself !!!!\n // because Q is bounded 1...N-1 !!!!!!!!!!\n // To achieve this we need to stop looking at specific GOAL states and COMBINE them into GOOD states and rest\n // are BAD states; this way we do not loop over N indexes as well !!!!!\n\n // there are 2 possibilities: after K operations: so define 2 DP transitions!!!!!\n // for num ways to get somewhere after K SHIFTS/STEPS; LET P = num good indexes; total choices for indexes = N\n // 1) end up NON-GOAL state f[k] = f[k-1]*(n-p-1) + g[k-1]*(n-p)\n // bad->any_other_bad good->bad\n // 2) end up at GOAL state g[k] = g[k-1]*(p-1) + f[k-1]*p\n // good->any_other_good bad->good\n // base case when K=0 depends on whether there is a match starting index 0 aka s == t\n\n // examples:\n // BGB\n // 01234567\n // abcdabcd start ways to each "cdab" with cost=2\n // bcda 1 p=1 start -> bcda -> cdab p=2 so 1+1\n // cdab 2 p=2 start -> dabc -> cdab p=2 so 3-1\n // dabc 3 p=3\n\n // BGBGB\n // 0123456789\n // abababababab START k = 1 ways = 2\n // ababab 0\n // ababab 2\n // ababab 4\n // ababab 6\n\n // However, this STILL requires looping over K !!!!!! K is too big !!!! need to take K OUT of the transition !!!!\n // so consolidate the transition as MATRIX equation:\n // let [n-p-1 n-p ] [bad->any_other_bad, good->bad]\n // M matrix = [ p p-1 ] [bad->good, good->any_other_good]\n // so:\n // (f,g)[k] = M * (f,g)[k-1]\n // but after K operations actually we get\n // (f,g)[k] = M^k * (f,g)[0]\n // and we know 2x2 matrix * 2x2 matrix = 2x2 matrix !!\n // so we just need to take the matrix to power K QUICKLY !!!!! fast exponentiation !!!!!!!\n\n // base case needs to convert M^K * (f,g)[0] -> [f\',g\'] the 2 results of both DP equations\n\n public int numberOfWays(String s, String t, long k) {\n if (k == 0) return s.equals(t) ? 1 : 0;\n String SS = s + s;\n int p = getNumGoodStatesKMP(SS, t); // num good states (goals)\n int n = s.length(); // num possible shifts\n System.out.println("numGoodStates: " + p);\n\n long[] m = new long[]{n - p - 1, n - p, p, p - 1};\n m = matrixPow(m, k);\n // base case k = 0: M*[0,1] 0 invalid, 1 valid state\n if (isMatchAt0) return (int) m[3];\n // base case k = 0: M*[1,0] 1 invalid, 0 valid state\n return (int) m[2];\n }\n\n\n // represent matrix as array:\n // a,b,c,d\n // is:\n // a,b\n // c,d\n\n // a0,a1 * b0,b1 = (a0*b0 + a1*b2) (a0*b1 + a1*b3)\n // a2,a3 b2,b3 (a2*b0 + a3*b2) (a2*b1 + a3*b3)\n long[] matrixMult(long[] a, long[] b) {\n long[] res = new long[4];\n res[0] = (a[0] * b[0] % M + a[1] * b[2] % M) % M;\n res[1] = (a[0] * b[1] % M + a[1] * b[3] % M) % M;\n res[2] = (a[2] * b[0] % M + a[3] * b[2] % M) % M;\n res[3] = (a[2] * b[1] % M + a[3] * b[3] % M) % M;\n return res;\n }\n\n long[] matrixPow(long[] m, long k) { // matrix^K // 1 0 base case: identity matrix !!!!\n if (k == 0) return new long[]{1, 0, 0, 1}; // 0 1\n long[] mKHalf = matrixPow(m, k / 2);\n mKHalf = matrixMult(mKHalf, mKHalf);\n if (k % 2 == 1) mKHalf = matrixMult(mKHalf, m);\n return mKHalf;\n }\n\n\n// int solveDpWays(int n, int tLen, int numGoodStates, long k) { // O(K)\n// n = n - tLen - 1;\n// long prevG = numGoodStates;\n// if (isMatchAt0) prevG--;\n// long prevF = n - numGoodStates;\n// int p = numGoodStates;\n//\n// for (int q = 1; q <= k; q++) {\n// long f = (prevF * (n - p - 1) % M + prevG * (n - p) % M) % M;\n// long g = (prevG * (p - 1) % M + prevF * p % M) % M;\n// prevG = g;\n// prevF = f;\n// }\n//\n// return (int) prevG;\n// }\n\n\n // Basically: dp[i][k] = num ways to reach rotation starting with i, using k steps\n // dp[i][k] = sum(dp[j][k-1]) where j != i\n // K is too big; take it out of the cache! only look back once anyway!\n\n// // K*N*N:\n// // for 1..K:\n// // 0: 1+2+3\n// // 1: 0+2+3\n// // 2: 0+1+3\n// // 3: 0+1+2\n// // each index is present (N-1) times\n// // dp[i][k] = sum(dp[_][k-1]) - dp[i][k-1]\n// long[] solveDpWays(int n, long k, int tLen) { // O(N*K)\n// long[] prevDp = new long[n];\n// long prevSum = 0;\n// for (int i = 1; i < n - tLen; i++) prevSum += prevDp[i] = 1;\n//\n// for (int q = 2; q <= k; q++) {\n// long[] dp = new long[n];\n// long sum = 0;\n// for (int i = 0; i < n - tLen; i++) {\n// dp[i] = (prevSum - prevDp[i] + M) % M;\n// sum = (sum + dp[i]) % M;\n// }\n// prevDp = dp;\n// prevSum = sum;\n// }\n//\n// return prevDp;\n// }\n\n// long[] solveDpWays(int n, long k, int tLen) { // O(K*N*N)\n// long[] prevDp = new long[n];\n// for (int i = 1; i < n - tLen; i++) prevDp[i] = 1;\n//\n// for (int q = 2; q <= k; q++) {\n// long[] dp = new long[n];\n// for (int i = 0; i < n - tLen; i++) {\n// for (int j = 0; j < n - tLen; j++) {\n// if (i == j) continue;\n// dp[i] += prevDp[j];\n// dp[i] %= M;\n// }\n// }\n// prevDp = dp;\n// }\n// return prevDp;\n// }\n\n\n // just KMP below:\n int getNumGoodStatesKMP(String SS, String t) {\n int[] lps = getLps(t);\n int tLen = t.length();\n int i = 0; // haystack SS\n int j = 0; // needle T\n int n = SS.length();\n int numGoodStates = 0;\n while (i + (tLen - j) < n) {\n if (SS.charAt(i) == t.charAt(j)) {\n i++;\n j++;\n } else {\n if (j == 0) {\n i++;\n } else {\n j = lps[j - 1];\n }\n }\n if (j == tLen) { // matched whole T; handle overlapping Ts inside SS !!!\n j = lps[j - 1]; // try to continue matching the prev lps again\n numGoodStates++;\n if (i == tLen) isMatchAt0 = true;\n }\n }\n return numGoodStates;\n }\n\n boolean isMatchAt0 = false;\n\n int[] getLps(String s) {\n int n = s.length();\n int[] lps = new int[n];\n int i = 1;\n int prevLps = 0;\n\n while (i < n) {\n if (s.charAt(i) == s.charAt(prevLps)) {\n prevLps++;\n lps[i++] = prevLps;\n } else {\n if (prevLps == 0) {\n lps[i++] = 0;\n } else {\n prevLps = lps[prevLps - 1];\n }\n }\n }\n return lps;\n }\n\n int M = (int) 1e9 + 7;\n\n}\n\n``` | 2 | 0 | ['Java'] | 0 |
string-transformation | O(n), no DP | on-no-dp-by-pvillano-ff03 | Intuition\nImportant observations:\n- Removing a suffix of s and appending it at the start of s is a rotation.\n- Using one rotation, s can be rotated to t in m | pvillano | NORMAL | 2023-09-11T21:51:33.078579+00:00 | 2023-09-11T21:51:33.078609+00:00 | 617 | false | # Intuition\nImportant observations:\n- Removing a suffix of s and appending it at the start of s is a rotation.\n- Using one rotation, s can be rotated to t in multiple ways only if s repeats.\n- The number of solutions "should" only depend on k and how many times s repeats (and if one exists)\n - However, the exclusion of a rotation by zero makes finding rotions that add to zero more complicated\n\n\n# Approach\nMy first method was slow. First, it created a list of target rotations which transformed s to t. Next it counted the number of ways to sum k rotations such that their sum was equal to each target rotation. It finally returned the sum of sums.\n\nI bet there would be a general formula for ways to add k rotations to a specific target rotation, so I made a table to look for a pattern. I used an s of length 4.\n```\n Target rotation:\n 0 1 2 3\n +-------------\nRound: 1 | 0 1 1 1\n 2 | 3 2 2 2\n 3 | 6 7 7 7 <-- Number of ways to get here\n 4 | 21 20 20 20\n 5 | 60 61 61 61\n```\nYou\'ll see two patterns, both of which I plugged into the [OEIS](https://oeis.org/). The zero column is [A054878](https://oeis.org/A054878) and the other columns are [A015518](https://oeis.org/A015518). I repeated this for an s of length 5 and found [A109499](https://oeis.org/A109499) and [A323266](https://oeis.org/A323266). From the formulae for these sequences I was able to derive the general formuale `ways_0` and `ways_1`\n\nThe idea of counting the number of ways a single rotation could transform s to t was discovered last. I had run into performance issues for the inputs "aaa...", "ababab..." and was looking for a way to identify these sequences. I did some funky list comprehension to see if s was composed of repeating pairs and eventually stumbled upon the thing I have now.\n\n# Complexity\n- Time complexity:\n$$O(n)$$: calls to `str.find`\n\n- Space complexity:\n$$O(n)$$: creation of ss\n\n# Code\n```python3\nclass Solution:\n def numberOfWays(self, s: str, t: str, k: int) -> int:\n n = len(s)\n ss = s + s\n first = ss.find(t)\n if first == -1:\n return 0\n elif first == 0:\n zero_targets = 1\n else:\n zero_targets = 0\n period = ss.find(s, 1)\n frequency = len(s) // period\n nonzero_targets = frequency - zero_targets\n MOD = 10 ** 9 + 7\n ways_0 = (pow(n - 1, k, MOD * n) + (n - 1) * ((-1) ** k)) // n\n ways_1 = (pow(n - 1, k, MOD * n) - ((-1) ** k)) // n\n return (zero_targets * ways_0 + nonzero_targets * ways_1) % MOD\n\n``` | 2 | 0 | ['Python3'] | 1 |
string-transformation | My solution (String Hashing + math) with external links to foundation knowledge | my-solution-string-hashing-math-with-ext-pkx3 | Reason of sharing solution\n Describe your first thoughts on how to solve this problem. \nI am shocked that leetcode contest have such problem that required hig | marvenlee | NORMAL | 2023-09-11T21:41:26.857226+00:00 | 2023-09-11T21:41:26.857257+00:00 | 99 | false | # Reason of sharing solution\n<!-- Describe your first thoughts on how to solve this problem. -->\nI am shocked that leetcode contest have such problem that required high math skill. Therefore, I am writing this solution with some of my suggested link to learn the foundation. Hopefully this solution would help people with knowledge gap to be able to solve this problem. Sorry for the my any bad english (I am writing solution to improve my english as well) .\nMy proposed solution required the following foundation knowledge\n1. String Hashing (https://cp-algorithms.com/string/string-hashing.html)solved string comparison problem with math\n2. Binary Exponential (https://cp-algorithms.com/algebra/binary-exp.html) compute $$a^b$$ in $$O(log b)$$\n3. Modular Multiplicative inverse with Fermat\'s Little Theorem (https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/) compute $$1/a \\mod m$$ in integer if $$m$$ is a prime\n4. Matrix Exponential (https://www.geeksforgeeks.org/matrix-exponentiation/) compute $$M^k$$ in $$O(n^2 log(k))$$ where M is Matrix with $$n \\times n$$ dimension\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTo solved this problem, I write the observation and how this observation is applied to solve the problem with detailed explaination of the steps.\n## Observation\n**There are only $$n$$ possible permutation of the string $$s$$ and an operation allow a string to be transformed into another $$n-1$$ possible permutation (except itself)** \n\nlet $$s=s_0s_1..s_{n-1}$$ The $$n$$ possible permuatation is a rotation of the string denote as $Rot(i, s)$ rotate the string i-th time on s.\nFor eg,\n$Rot(0, s) = s_0s_1s_2...s_{n-1}$, \n$Rot(1, s) = s_1s_2...s_{n-1}s_0$,\n$Rot(2, s) = s_2s_3...s_{n-1}s_0s_1$,\n... \n$Rot(i, s) = s_is_{i+1}...s_{n-1}s_0...s_{i-1}$, \n...\n$Rot(n - 1, s) = s_{n-1}s_0s_1...s_{n-2}$. \n\nif $$i = (j + k) % n$$ then $$Rot(i, s) = Rot(j, Rot(k, s))$$\nYou can easily see that the operation mentioned in the question is equilvalence to applying the operation $Rot(n - l, s)$\n\n*Note that Rot(0,s) is not allowed as $0<l<n$\n\n## Applying Observation into problem\nSo you just simply sum up the possible number of ways to become string, $$Rot(i, s)$$ if $$Rot(i, s) = t$$, $$t is the target string$$\n\nStep 1: Check if $$Rot(i, s) == t$$\nStep 2: Calculate the number of ways to transformed to $$Rot(i, s)$$ after $$k$$ operation\nStep 3: Sum up the number of ways.\n\n## Solving Step 1, Check if $$Rot(i, s) == t$$\nAs comparing two string is $$O(n)$$ in worst case scenario and there are $$n$$ string to compared. Therefore a brute force string rotation and comparisong would results in $$O(n^2)$$.\n\nThe approach I use here is **Rolling Hash**\nYou can refer to https://cp-algorithms.com/string/string-hashing.html.\n\nTo calculate the hash of the string, $$Rot(i, s)$$,\nNotice that\n$$Rot(0, s) = (s_0 + s_1 \\cdot p^1 + s_2 \\cdot p^2 + ... + s_{n-1} \\cdot p^{n-1}) \\mod m= \\sum_{i = 0}^{n-1}{s_i \\cdot p^{i - i}} \\mod m$$ \n$$Rot(1, s) = (s_1 + s_2 \\cdot p^1 + ... + s_{n-1} \\cdot p^{n-2} + s_{0} \\cdot p^{n-1}) \\mod m = (\\frac{Rot(0,s) - s_0}{p} + s_{0} \\cdot p^{n-1}) \\mod m$$\n\nTherefore, in general, $$Rot(i,s) = (\\frac{Rot(i - 1,s) - s_{i - 1}}{p} + s_{i - 1} \\cdot p^{n-1}) \\mod m$$, for $$0 < i < n$$\n\nHowever, to implement this equation in code, you need to know \n1. **Binary Exponential** (https://cp-algorithms.com/algebra/binary-exp.html) where this algorithm compute $$p^{i}$$ in $$O(log(i)$$)\n2. **Modular Multiplicative inverse with Fermat\'s Little Theorem** (https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/) where this algorithm compute the integer $$Inv(p) = {1}/{p} \\mod m = p^{m-2}$$, $$Inv(p)$$ is the modular multiplicative inverse of $$p$$ \n\nTo compute hash of $$s$$ and hash of $$t$$ would required $$O(n)$$ and\nthis transformation and comparing whether the hash of $$Rot(i,s)$$ is equal to hash of $$t$$ would required $$O(1)$$ if we precompute $$p^{i}$$ and $$inv(p)$$. Therefore this step would required $$O(n)$$\n\n## Solving Step 2, Calculate the number of ways to transformed to $$Rot(i, s)$$ after $$k$$ operation\nDenote the number of ways to transform into $$Rot(i,s)$$ after $$k$$ operation as $$Num(i, k)$$\n\n\nyou can see that $$Num(1,k) = Num(2,k) = ... = Num(n - 1, k)$$ So for easier notation purpose,Let $$A(k) = Num(1,k)$$ and $$B(k) = Num(0,k)$$\n\n$$A(k) = (n - 2) \\cdot A(k - 1) + B(k - 1)$$\n$$B(k) = (n - 1) \\cdot A(k - 1)$$\n\nYou can use matrix exponential method mentioned in other solution to solve this recurrence equation (https://www.geeksforgeeks.org/matrix-exponentiation/)\n\n\n\nor solve the recurrence equation using math.\nIts a bit messy (sorry), I use a lot of time to solve it, highly recommend the matrix method. Anyway at last the equation is\n$$A(k) = \\frac{(n-1)^k - (-1)^k}{n}$$\n$$B(k) = A(k) + (-1)^k$$\nSo you can solve this using modular multiplicative inverse and binary exponential and split the case where $$k$$ is odd or $$k$$ is even\n\n\n\nSolving using matrix exponential or the equation required $$O(log k)$$ time complexity\n \n## Solving Step 3, Sum up number of ways.\nDenote $$x$$ the number of rotation strings that is same as $$t$$ (except the original string $$s$$).\nDenote $$y$$ as 1 if $$s$$ = $$t$$, 0 otherwise.\n*Both of this can be calculated from Step 1.\n\nThe answer is $$x * A(k) + y * B(k)$$\nwith final time complexity $$O(n + log k)$$\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n + log(k))$$\n- Space complexity:\n$$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n using ll = long long;\n const ll p = 29;\n const ll m = 1e9 + 7;\n const ll N = 500002;\n ll p_pow[500002];\n ll inv_p;\n \n ll binpow(ll a, ll b){\n if(b == 0) return 1;\n // a ^ b\n // (a ^ (b/2)) * (a ^ (b/2)) * a(if )\n \n ll x = binpow(a, b/2);\n return ((x * x) % m * ((b % 2 == 0)?1:a))% m;\n \n }\n \n ll modInv(ll a){\n return binpow(a, m - 2);\n }\n \n ll hash(string s){\n ll val = 0;\n for(int i = 0; i < s.size(); i++){\n val += (s[i] - \'a\') * p_pow[i];\n val %= m;\n }\n return val;\n }\n \n int numberOfWays(string s, string t, long long k) {\n p_pow[0] = 1;\n \n for(int i = 1; i < N; i++){\n p_pow[i] = (p_pow[i - 1] * p ) % m;\n }\n \n inv_p = modInv(p);\n \n \n int n = s.size();\n // pow(n - 1, k) * number of arragement that is same as t;\n // all equal case.\n int num = 0;\n ll ans = 0;\n \n ll notSame = ( (binpow(n - 1, k)) + ((k % 2 == 0)?-1:1) + m) * modInv(n) % m;\n ll Same = (notSame + ((k % 2 == 0)?1:-1) + m ) % m;\n \n ll hash_s = hash(s), hash_t = hash(t);\n \n if(hash_s == hash_t) {\n ans += Same;\n }\n \n for(int i = 0; i < n - 1; i++){\n hash_s = (hash_s + m - (s[i] - \'a\') ) % m;\n hash_s *= inv_p;\n hash_s %= m;\n hash_s += (s[i] - \'a\') * p_pow[n - 1];\n hash_s %= m;\n \n // cout << hash_s << " " << hash_t << "\\n";\n if(hash_s == hash_t) num++;\n }\n \n // cout << num << " " << Same << " " << notSame << "\\n";\n \n ans += (num * notSame) % m;\n \n return ans % m;\n }\n};\n``` | 2 | 0 | ['Math', 'Rolling Hash', 'Matrix', 'C++'] | 0 |
string-transformation | Python3 | Super Short Solution - O(n + logk) | Math + KMP | python3-super-short-solution-on-logk-mat-oefq | Intuition\nOperation = rotation, but no identical rotation\nTherefore, there are\n $f(k)$ combinations to get any $rotation \neq s$\n $f\prime(k) = (n-1) \cdot | deimvis | NORMAL | 2023-09-10T22:32:21.913831+00:00 | 2023-09-10T22:33:31.212856+00:00 | 1,981 | false | # Intuition\nOperation = rotation, but no identical rotation\nTherefore, there are\n* $f(k)$ combinations to get any $rotation \\neq s$\n* $f\\prime(k) = (n-1) \\cdot f(k-1)$ combinations to get $rotation = s$\n\n# Approach = Math + KMP\n* $f(k) = \\frac{(n-1)^k - (-1)^k}{n}$ (similarly as in the [video](https://www.youtube.com/watch?v=DxJe-9QU0vk&ab_channel=Zak%27sLab))\n* number of non-identical rotations of $s$ equal to $t$ = number of substrings in $t[1:] + t[:-1]$ equal to $s$ $\\Longrightarrow$ use [KMP](https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm)\n\n# Complexity\n- Time complexity: $O(n + \\log k)$\n\n- Space complexity: $O(n)$\n\n# Code\n```\nclass Solution:\n def numberOfWays(self, s: str, t: str, k: int) -> int:\n MOD = 10**9 + 7\n\n n = len(s)\n # similar to fibonacci explicit formula: https://www.youtube.com/watch?v=DxJe-9QU0vk&ab_channel=Zak%27sLab\n def f(k_):\n return (pow(n-1, k_, MOD) - pow(-1, k_)) * pow(n, -1, MOD)\n \n ans = 0\n if s == t:\n ans += (n-1) * f(k-1)\n cnt = self.kmp(t[1:] + t[:-1], s)\n ans += cnt * f(k)\n return ans % MOD\n\n # ----\n # the rest is KMP\n # https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm\n def kmp(self, text, word):\n cnt = 0\n z = self.calc_z(word)\n i = 0\n j = 0\n while i < len(text):\n if word[j] != text[i]:\n j = z[j]\n if j < 0:\n i += 1\n j += 1\n continue\n i += 1\n j += 1\n if j == len(word):\n cnt += 1\n j = z[j]\n return cnt\n \n def calc_z(self, s):\n z = [None for _ in range(len(s)+1)]\n z[0] = -1\n i = 1\n j = 0\n \n while i < len(s):\n if s[i] == s[j]:\n z[i] = z[j]\n else:\n z[i] = j\n while j >= 0 and s[i] != s[j]:\n j = z[j]\n i += 1\n j += 1\n z[i] = j\n return z\n\n``` | 2 | 0 | ['Python3'] | 0 |
string-transformation | Rabin-Karp Rolling Hash + Math in Python with Explanation | rabin-karp-rolling-hash-math-in-python-w-wc3x | Approach\n Describe your first thoughts on how to solve this problem. \nFirst we need to find the number of answer positions i that make s[i:i+n] == t. Any effi | metaphysicalist | NORMAL | 2023-12-21T16:50:03.035311+00:00 | 2023-12-21T16:50:03.035342+00:00 | 81 | false | # Approach\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst we need to find the number of <b>answer</b> positions `i` that make `s[i:i+n] == t`. Any efficient string matching can be applied. My solution employs the Rabin-Karp rolling hash for string matching. \n\nThen, a little math is used to solve the problem. We maintain a small $2 \\times 2$ matrix $M$ representing the transitions from a position to another position. A position is either non-answer (`0`) or answer (`1`). The number of answer positions obtained by rolling hash is `x`, and the length of the input string `t` is `n`.\n\n$$\nM = \\begin{bmatrix}\na & b\\\\\nc & d\n\\end{bmatrix} \n= \n\\begin{bmatrix}\nn-x-1 & x\\\\\nn-x & x-1\n\\end{bmatrix} \n$$\n\n- $a$ is the ways from a non-answer position to another non-answer position.\n- $b$ is the ways from a non-answer position to an answer position.\n- $c$ is the ways from an answer position to a non-answer position.\n- $d$ is the ways from an answer position to another answer position. \n\nConsequently, the total ways to reach an answer position after exactly `k` steps is $M^k_{0,1}$ if we start from a non-answer position (i.e., `s != t`) or $M^k_{1,1}$ if we start from an answer position (i.e., `s == t`). One more thing is $M^k$, which can be efficiently obtained in $O(\\log k)$ with the technique of exponentiation by squaring. \n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $O(n) + O(\\log k)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nimport numpy as np\n\nclass Solution:\n def numberOfWays(self, s: str, t: str, k: int) -> int:\n def matrix_pow(m, k):\n if k == 1:\n return m\n h = matrix_pow(m, k//2)\n if k % 2 == 0:\n return np.matmul(h, h) % 1000000007\n else:\n return np.matmul(np.matmul(h, h) % 1000000007, m) % 1000000007\n\n n = len(s)\n P = 31\n M = 1000000009+9\n p_pow_n = pow(P, n, M)\n ht = 0\n ord_a = ord(\'a\')\n for c in t:\n ht = (ht * P + (ord(c) - ord_a + 1)) % M\n targets = 0\n hs = 0\n for i, c in enumerate(s+s):\n hs = (hs * P + (ord(c) - ord_a + 1)) % M\n if i >= n:\n hs = (hs - (ord(s[i-n]) - ord_a + 1) * p_pow_n) % M\n if ht == hs:\n targets += 1\n if targets == 0:\n return 0\n src = 1 if t == s[:n] else 0\n m = matrix_pow(np.array([[n - targets - 1, targets], [n - targets, targets - 1]]), k)\n return m[src][1]\n``` | 1 | 0 | ['Math', 'Divide and Conquer', 'Rolling Hash', 'String Matching', 'Python3'] | 0 |
string-transformation | Notes showing steps to come up to a solution | Matrix Exponentiation | KMP | notes-showing-steps-to-come-up-to-a-solu-ls1b | Intuition\nIt took me a while to figure out the solution and there are excellent solutions posted by other experienced people.\nThe note shows the process I too | cold_coffee | NORMAL | 2023-09-15T05:23:42.029307+00:00 | 2023-09-15T05:23:42.029336+00:00 | 115 | false | # Intuition\nIt took me a while to figure out the solution and there are excellent solutions posted by other experienced people.\nThe note shows the process I took to finally come to the solution.\n\n# Approach\n\n\n\n# Complexity\n- Time complexity:\nO(N * log(k))\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution {\npublic:\n int mod = 1e9 + 7;\n\n vector<int> find(string s, string t) {\n string str = t + \'#\' + s + s;\n vector<int> prefix(str.length()), ret;\n int j;\n for(int i=1; i<str.length(); i++) {\n j = prefix[i-1];\n while(j>0 && str[i] != str[j]) \n j = prefix[j-1];\n\n if(str[i] == str[j])\n j++;\n\n prefix[i] = j;\n if(i > s.size() && j == s.size()) {\n if(i - 2*s.size() < s.size())\n ret.push_back(i - 2*s.size()); \n }\n }\n\n return ret;\n }\n\n vector<vector<long long>> exponentiate(vector<vector<long long>> a, long long x) {\n vector<vector<long long>> ans = {{1, 0}, {0, 1}};\n while(x > 0) {\n if(x & 1) \n ans = multiply(ans, a);\n a = multiply(a, a);\n x >>= 1;\n }\n return ans;\n }\n\n vector<vector<long long>> multiply(vector<vector<long long>> a, vector<vector<long long>> b) {\n vector<vector<long long>> ans = {{0, 0}, {0, 0}};\n for (int i = 0; i < 2; i++)\n for (int j = 0; j < 2; j++) \n for (int k = 0; k < 2; k++) \n ans[i][j] = (ans[i][j] + a[i][k] * b[k][j]) % mod;\n \n return ans;\n }\n\n\n\n int numberOfWays(string s, string t, long long k) {\n int n = s.size();\n vector<int> ind = find(s, t);\n vector<vector<long long>> mat = {{0, n-1}, {1, n-2}};\n mat = exponentiate(mat, k);\n\n long long a = mat[0][0];\n long long b = mat[1][0];\n\n long long result = 0;\n for(int i : ind) {\n result = result + ((i == 0) ? a : b);\n result %= mod;\n } \n\n return result;\n }\n};\n``` | 1 | 0 | ['String Matching', 'C++'] | 0 |
string-transformation | Python, analytical (insights + math), O(n + log(k)), beats 100% | python-analytical-insights-math-on-logk-w6e72 | Intuition\n1. Observation #1\nRegardless how many times we do operation we always end up in some "sufix-to-pref" position (more formally s->s[i:]+s[:i]). Which | raggzy | NORMAL | 2023-09-11T02:52:56.390570+00:00 | 2023-09-11T03:19:51.962016+00:00 | 93 | false | # Intuition\n1. Observation #1\nRegardless how many times we do operation we always end up in some "sufix-to-pref" position (more formally `s->s[i:]+s[:i]`). Which means end strings differ only in that "split" position (`i`). So we kind of want to track how many ways would end in each position.\n2. Observation #2\nIf string `s+s` does not contain `t`, then there is no solution (`0` ways). Let\'s assume `s+s` contains `t`, and `i1` - index of first occurence.\n3. Observation #3 (cycles)\nLet\'s find minimum `cl` such that `s=s[cl:]+s[:cl]` (e.g. `cl=2` for string `ababab`, or `cl=4` for string `abcd`). If we have `cl<n` it means we not only care about `i1` position but also `i1+cl`, `i1+2*cl` and so on (we care about all `(i1+j*cl)%n` positions)\n4. Now let\'s describe how we track amount of ways to get `i` position in `k` moves.\nLet\'s define `ways[i]` - count of ways to get `i`-position after `k` moves.\nAt the beginning (`k=0`) we can get only `i=0`. So `ways=[1,0,0...0]`. \nTo get `ways` for `k+1` moves - we use recursive formula `ways[i]=sum(ways)-ways[i]` basically meaning we can get `i` position at step `k+1` from every `i` position at step `k` except self. Since `k` is large - we need to improve this. Let\'s see how it evolves with time\n```\n k=0: ways=[1, 0,0,...,0] # sum = 1\n k=1: ways=[0, 1,1,...,1] # sum = n-1\n k=2: ways=[n-1, n-2,...,n-2] # sum = (n-1) ** 2\n k=3: ways=[(n-1) ** 2 - (n-1), (n-1) ** 2 - (n-2),...] # sum = (n-1)**3\n```\nSo depending on `k` we have `ways[0]=ways[i]+1` or `ways[1]=ways[0]+1` and `sum(ways)==(n-1) ** k`, and all `ways[i>=1]`are equal. \nOr more formally we redefine `f0 = ways[0]` and `fn0 = ways[i>=1]`, and we have equations `f0 + (n-1)*fn0 = (n-1) ** k` and `fn0=f0+1` or `f0=fn0+1`.\n\nSo in the end we care about `ways[i1+j*cl]` or `n/cl` total positions. And one of them may be `0` (if `i1==0`).\n\n# Approach\nSee the code, it implements ideas in intuition + uses some modulo arithmetics (`a/b (% MOD) = a * b_inv (%MOD)`, `b_inv = pow(b,MOD-2,MOD`)\n\n# Complexity\n- Time complexity: `O(n+log(k))` - we assume `find` is KMP-like algo (Python 3.10+), and `pow(a,b,MOD)` uses fast power algo (which is the case).\n- Space complexity: `O(n)`\n\n# Code\n```\nclass Solution:\n def numberOfWays(self, s: str, t: str, k: int) -> int:\n MOD=10**9+7\n n=len(s)\n s2=s+s\n i1=s2.find(t)\n # check if there is occurrence\n if i1==-1: return 0\n i2=s2.find(t, i1+1)\n # check if we have cycle\n cl=n if i2==-1 else (i2-i1)\n if k%2==0:\n # f0=fn0+1\n # fn0+1+fn0*(n-1)=(n-1)**k\n # fn0 = ((n-1)**k-1)/n\n fn0 = (pow(n-1,k,MOD) - 1)*pow(n,MOD-2,MOD)\n f0=fn0+1\n else:\n # fn0=f0+1\n # f0+(f0+1)*(n-1)=(n-1)**k\n # f0=((n-1)**k - n + 1)/n\n f0 = (pow(n-1,k,MOD) - n + 1)*pow(n,MOD-2,MOD)\n fn0 = f0+1\n # check if 0-position is valid\n return (fn0 * (n//cl-1) + (f0 if i1==0 else fn0))%MOD\n \n \n``` | 1 | 0 | ['Python3'] | 0 |
string-transformation | Efficient Cyclical Pattern Matching: A Novel KMP Approach with Dynamic Frequency Calculation | efficient-cyclical-pattern-matching-a-no-19wx | Intuition\nWhen presented with the problem of finding the number of ways two strings can match based on a given pattern, my initial instinct was to use the Knut | janis__ | NORMAL | 2023-09-10T11:09:17.739156+00:00 | 2023-09-10T11:09:17.739174+00:00 | 96 | false | # Intuition\nWhen presented with the problem of finding the number of ways two strings can match based on a given pattern, my initial instinct was to use the Knuth-Morris-Pratt (KMP) algorithm. The KMP algorithm is a powerful tool for pattern searching and can identify all occurrences of a pattern in a text in linear time.\nBy extending the string s with itself (excluding the last character) as s + s[:-1], I aimed to handle the case where the string is cyclical. This way, the KMP algorithm can efficiently detect the matches without manually rotating and comparing the strings for each position.\nThe given value k further complicates the problem. This requires us to adjust our calculations based on the power of k and the length of the text. Modulo arithmetic ensures the results are within a manageable range.\n\n# Approach\nKMP Preparation:\nBefore employing the KMP search, I first construct a prefix array of the pattern (in this case, string t) using the buildPrefixArray function. This array, often called the "failure function" or "partial match table", will aid in skipping unnecessary comparisons when searching for the pattern.\nKMP Search: Using the prepared prefix array, the kmpSearch function scans through the extended text s + s[:-1]. Upon identifying a full match of the pattern, it yields the starting position of that match.\nFrequency Calculation: Calculate frequency1 and frequency0 based on the provided formula. These frequencies help in determining how often we can expect the pattern to match based on the value of k.\nTotal Matches:Finally, iterate through the starting positions yielded by the KMP search. Depending on the position, either frequency1 or frequency0 is added to the total count. This total count represents the number of ways the pattern can be found in the text.\n\n# Complexity\n- Time complexity:\nThe primary operations are the KMP pattern searching and prefix array construction, both of which operate in linear time. Hence, the overall time complexity is O(n)O(n), where nn is the length of the string s.\n\n- Space complexity:\n The space-consuming elements in the code are the prefix array in the KMP algorithm and the extended text string. Both of these elements grow linearly with the input. Therefore, the space complexity is O(n)O(n).\n\n# Code\n```\nclass StringAlgorithm:\n def buildPrefixArray(self, pattern: str) -> list[int]:\n prefixArray = [0] * len(pattern)\n j = 0\n for i in range(1, len(pattern)):\n while j > 0 and pattern[j] != pattern[i]:\n j = prefixArray[j - 1]\n if pattern[j] == pattern[i]:\n j += 1\n prefixArray[i] = j\n return prefixArray\n\n def kmpSearch(self, text: str, pattern: str):\n prefixArray = self.buildPrefixArray(pattern)\n textLength, patternLength, patternIndex = len(text), len(pattern), 0\n for i in range(textLength):\n while patternIndex >= patternLength or (patternIndex > 0 and text[i] != pattern[patternIndex]):\n patternIndex = prefixArray[patternIndex - 1]\n if text[i] == pattern[patternIndex]:\n patternIndex += 1\n if patternIndex == patternLength:\n yield i - patternLength + 1\n\nclass Solution:\n def numberOfWays(self, s: str, t: str, k: int) -> int:\n MODULUS = 10**9 + 7\n textLength = len(s)\n\n adjustment = (k % 2 * 2 - 1)\n frequency1 = (pow(textLength - 1, k, MODULUS) + adjustment + MODULUS) * pow(textLength, MODULUS - 2, MODULUS) % MODULUS\n frequency0 = (frequency1 - adjustment + MODULUS) % MODULUS\n\n total = 0\n for position in StringAlgorithm().kmpSearch(s + s[:-1], t):\n total += frequency1 if position else frequency0\n total %= MODULUS\n \n return total\n\n``` | 1 | 1 | ['Python3'] | 0 |
string-transformation | [Java] KMP + Matrix QuickPow, O(n + logk), 54ms | java-kmp-matrix-quickpow-on-logk-54ms-by-einy | \nclass Solution {\n // time = O(n + logk), space = O(n)\n final int mod = (int)1e9 + 7;\n long[][] g;\n public int numberOfWays(String s, String t, | silentwings | NORMAL | 2023-09-10T06:51:53.967406+00:00 | 2024-02-02T08:36:19.684375+00:00 | 505 | false | ```\nclass Solution {\n // time = O(n + logk), space = O(n)\n final int mod = (int)1e9 + 7;\n long[][] g;\n public int numberOfWays(String s, String t, long k) {\n int n = s.length();\n int v = kmp(s + s, t);\n g = new long[][]{{v - 1, v}, {n - v, n - 1 - v}};\n long[][] f = qmi(k);\n return s.equals(t) ? (int)f[0][0] : (int)f[0][1];\n }\n\n private int kmp(String s, String p) {\n int n = p.length(), m = s.length();\n s = "#" + s;\n p = "#" + p;\n int[] ne = new int[n + 1];\n for (int i = 2, j = 0; i <= n; i++) {\n while (j > 0 && p.charAt(i) != p.charAt(j + 1)) j = ne[j];\n if (p.charAt(i) == p.charAt(j + 1)) j++;\n ne[i] = j;\n }\n\n int cnt = 0;\n for (int i = 1, j = 0; i <= m; i++) {\n while (j > 0 && s.charAt(i) != p.charAt(j + 1)) j = ne[j];\n if (s.charAt(i) == p.charAt(j + 1)) j++;\n if (j == n) {\n if (i - n + 1 <= m / 2) cnt++;\n j = ne[j];\n }\n }\n return cnt;\n }\n\n private void mul(long[][] c, long[][] a, long[][] b) {\n long[][] t = new long[2][2];\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n for (int k = 0; k < 2; k++) {\n t[i][j] = (t[i][j] + a[i][k] * b[k][j]) % mod;\n }\n }\n }\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 2; j++) {\n c[i][j] = t[i][j];\n }\n }\n }\n\n private long[][] qmi(long k) {\n long[][] f = new long[2][2];\n f[0][0] = 1;\n while (k > 0) {\n if ((k & 1) == 1) mul(f, f, g);\n mul(g, g, g);\n k >>= 1;\n }\n return f;\n }\n}\n``` | 1 | 0 | ['Java'] | 1 |
string-transformation | Matrix Exp. + Z-Algo | matrix-exp-z-algo-by-dnitin28-ax5p | \n# Code\n\nclass Solution {\npublic:\n const int mod = 1e9 + 7;\n vector<int> zAlgo(string s){\n int n = s.size();\n vector<int> Z(n);\n | gyrFalcon__ | NORMAL | 2023-09-10T06:13:33.280695+00:00 | 2023-09-10T06:13:33.280729+00:00 | 259 | false | \n# Code\n```\nclass Solution {\npublic:\n const int mod = 1e9 + 7;\n vector<int> zAlgo(string s){\n int n = s.size();\n vector<int> Z(n);\n int l = 0, r = 0;\n for(int i=1;i<n;i++){\n if(i <= r){\n Z[i] = min(Z[i-l], r-i+1);\n }\n while(i+Z[i] < n and s[Z[i]] == s[i+Z[i]]){\n Z[i] ++;\n }\n if(i+Z[i]-1 > r){\n l = i;\n r = i + Z[i] - 1;\n }\n }\n return Z;\n }\n vector<vector<int>> matMul(vector<vector<int>>& a, vector<vector<int>>& b){\n vector<vector<int>> ans(2, vector<int>(2));\n ans[0][0] = ((1ll * a[0][0] * b[0][0])%mod + (1ll * a[0][1] * b[1][0])%mod)%mod;\n ans[0][1] = ((1ll * a[0][0] * b[0][1])%mod + (1ll * a[0][1] * b[1][1])%mod)%mod;\n ans[1][0] = ((1ll * a[1][0] * b[0][0])%mod + (1ll * a[1][1] * b[1][0])%mod)%mod;\n ans[1][1] = ((1ll * a[1][0] * b[0][1])%mod + (1ll * a[1][1] * b[1][1])%mod)%mod;\n return ans; \n }\n vector<vector<int>> matExp(vector<vector<int>>& a, long long b){\n vector<vector<int>> ans = a;\n while(b > 0){\n if(b%2){\n ans = matMul(ans, a);\n b --;\n }\n else{\n a = matMul(a, a);\n b /= 2;\n }\n }\n return ans;\n }\n int numberOfWays(string src, string tar, long long k) {\n int n = src.size();\n if((int)tar.size() != n){\n return 0;\n }\n\n int x = 0;\n string S = tar;\n S += src;\n S += src;\n std::vector<int> Z = zAlgo(S);\n for(int i=n;i<2*n;i++){\n if(Z[i] >= n){\n x ++;\n }\n } \n vector<vector<int>> mat(2, vector<int>(2));\n mat[0][0] = x-1, mat[0][1] = x, mat[1][0] = n-x, mat[1][1] = n-x-1;\n\n vector<int> V(2);\n if(src == tar){\n V[0] = 1;\n V[1] = 0;\n }\n else{\n V[0] = 0;\n V[1] = 1;\n }\n vector<vector<int>> ans = matExp(mat, k-1);\n int sol = ((1ll * ans[0][0] * V[0])%mod + (1ll * ans[0][1] * V[1])%mod)%mod;\n return sol;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
string-transformation | Python solution | python-solution-by-vilmos_prokaj-16cq | Intuition\nSimilar to other solutions. It finds the matches, then computes the number of possibilities for each possible match. For matrix exponentiation it use | vilmos_prokaj | NORMAL | 2023-09-10T05:45:51.948649+00:00 | 2023-09-10T05:45:51.948667+00:00 | 930 | false | # Intuition\nSimilar to other solutions. It finds the matches, then computes the number of possibilities for each possible match. For matrix exponentiation it uses that \n$$\n A=\\begin{pmatrix}\nn-2 & n-1\\\\ 1 & 0\n\\end{pmatrix}\n$$\nthe characteristic polynomial is $A^2-(n-1)A-(n-2)I=0$. The power is returned in the form $\\text{coeff1}\\times A+\\text{coeff0} \\times I$ and it turns out to be the bottom row of the power matrix (we need exactly this for counting).\n\n\n\n\n# Complexity\n- Time complexity: $$O(n+\\log k)$$\n $$O(n)$$ for matching and $$\\log k$$ for the matrix power.\n\n- Space complexity: $$O(n)$$\n\n\n# Code\n```\nP = 1_000_000_007\n\ndef mat_pow_2x2(a, b, k):\n res1, res0 = 0, 1\n pow1, pow0 = 1, 0\n while k > 0:\n if k&1:\n c = res1*pow1\n res1, res0 = (c*a+res1*pow0+res0*pow1) % P , (c*b+res0*pow0) % P\n c = pow1*pow1\n pow1, pow0 = (c*a+2*pow1*pow0) % P , (c*b+pow0*pow0) % P\n k >>= 1\n return res1, res0\n\ndef self_matches(s):\n n = len(s)\n self_match = [0]*n\n for i in range(1, n):\n j = self_match[i-1]\n ch = s[i]\n while j > 0 and s[j] != ch:\n j = self_match[j-1]\n self_match[i] = j + int(ch==s[j])\n return self_match\n\n\nclass Solution:\n def numberOfWays(self, s: str, t: str, k: int) -> int:\n\n matches = self_matches(s+"A"+t+t)\n\n n = len(s)\n total = 0\n coeff1, coeff0 = mat_pow_2x2(n-2, (n-1), k)\n\n for i in range(2*n,3*n):\n match_len = matches[i]\n if match_len >= n:\n if i == 2*n:\n total += coeff0\n else:\n total += coeff1\n return total % P\n \n``` | 1 | 0 | ['Python3'] | 0 |
string-transformation | Java Solution with explanation - beats 97% of submissions | java-solution-with-explanation-beats-97-2vcse | IntuitionRemoving the suffix of the string and putting it in the front is nothing but string rotation.Ideally, create string s + s and finding all count's of st | kodekrafter | NORMAL | 2025-02-28T16:39:45.984688+00:00 | 2025-02-28T16:39:45.984688+00:00 | 36 | false | # Intuition
Removing the suffix of the string and putting it in the front is nothing but string rotation.
Ideally, create string `s` + `s` and finding all `count`'s of string `t` would give how many occurences of `t` are possible when applying rotations to string `s`.
Once this is done, there are state transitions that should be considered and raised to the exponent/power of `k`.
# Approach
There are few things that are required to understand this solution:
1) To count the occurences of substring an efficient algorithm like Knuth-Morris-Pratt string matching or Z-Algorithm is needed.
2) Matrix exponentiation & Matrix multiplication algorithm is needed
Once the `count` of the substring (`t`) is found we create the following state table:
```java
long[][] state = {
{count - 1, count},
{n - count, n - count - 1}
};
```
What are these states?
State 0: Current string equals target string t
State 1: Current string doesn't equal target string t
[0][0] = count-1: Probability of going from state 0 → state 0
If we're currently at t, after a shift, how many ways can we still be at t?
There are "count" total positions where t appears in the doubled string
But we're already at one of those positions, so only "count-1" remain
[0][1] = count: Probability of going from state 1 → state 0
If we're currently NOT at t, after a shift, how many ways can we reach t?
There are exactly "count" positions where t appears in the doubled string
[1][0] = n-count: Probability of going from state 0 → state 1
If we're currently at t, after a shift, how many ways can we end up NOT at t?
Out of n possible shifts, "count" lead to t, so "n-count" don't lead to t
[1][1] = n-count-1: Probability of going from state 1 → state 1
If we're currently NOT at t, after a shift, how many ways can we still NOT be at t?
Out of n-1 remaining shifts, "count" lead to t, so "n-count-1" don't lead to t
After this it's just the matrix exponentation of this `state` matrix and return the result.
When returning the result we check if the string `s` already equal to `t` and make appropriate choices while returning the result.
# Complexity
- Time complexity: $$O(n + log(k))$$
- Space complexity: $$O(n)$$
# Code
```java []
class Solution {
public static final int MOD = 1_000_000_007;
public int numberOfWays(String s, String t, long k) {
int n = s.length();
String s1 = s + s.substring(0, n - 1);
int count = countWays(s1, t);
long[][] state = {
{count - 1, count},
{n - count, n - count - 1}
};
long[][] res = matrixExp(state, k);
if (s.equals(t)) return (int) res[0][0];
return (int) res[0][1];
}
private int countWays(String s, String t) {
if (s == null || t == null || s.trim().length() == 0 || t.trim().length() == 0)
return -1;
int n = s.length();
int m = t.length();
int i = 0, j = 0;
int count = 0;
int[] lps = computeLPS(t);
while (i < n) {
if (s.charAt(i) == t.charAt(j)) {
++i;
++j;
if (j == m) {
++count;
j = lps[j - 1];
}
} else {
if (j != 0) {
j = lps[j - 1];
} else {
++i;
}
}
}
return count;
}
private int[] computeLPS(String t) {
int n = t.length();
int[] lps = new int[n];
lps[0] = 0;
int i = 1, j = 0;
while (i < n) {
if (t.charAt(i) == t.charAt(j)) {
++j;
lps[i] = j;
++i;
} else {
if (j != 0) {
j = lps[j - 1];
} else {
++i;
}
}
}
return lps;
}
private long[][] matrixMul(long[][] A, long[][] B) {
int nRowsA = A.length;
int nColsA = A[0].length;
int nRowsB = B.length;
int nColsB = B[0].length;
if (nColsA != nRowsB) return null;
long[][] C = new long[nRowsA][nColsB];
for (int i = 0; i < nRowsA; ++i) {
for (int j = 0; j < nColsB; ++j) {
for (int k = 0; k < nColsA; ++k) {
C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % MOD;
}
}
}
return C;
}
private long[][] matrixExp(long[][] A, long exp) {
int n = A.length;
long[][] res = new long[n][n];
for (int i = 0; i < n; ++i) {
res[i][i] = 1;
}
while (exp > 0) {
if ((exp & 1) > 0) {
res = matrixMul(res, A);
}
exp >>= 1;
A = matrixMul(A, A);
}
return res;
}
}
```
``` python
class Solution:
def numberOfWays(self, s: str, t: str, k: int) -> int:
s1 = s + s
s1 = s1[: len(s1) - 1]
n = len(s)
count = self.kmp(s1, t)
state_matrix = [[count - 1, count], [n - count, n - count - 1]]
res = self.matrix_exp(state_matrix, k)
return res[0][0] if s == t else res[0][1]
def kmp(self, s: str, t: str) -> int:
if not s or not t:
return -1
lps = self.compute_lps(t)
count = 0
n, m = len(s), len(t)
i, j = 0, 0
while i < n:
if s[i] == t[j]:
i += 1
j += 1
if j == m:
count += 1
j = lps[j - 1] # should this be reset to 0?
else:
if j != 0:
j = lps[j - 1]
else:
i += 1
return count
def compute_lps(self, t: str) -> List[int]:
i, j = 1, 0
n = len(t)
lps = [0] * n
while i < n:
if t[i] == t[j]:
j += 1
lps[i] = j
i += 1
else:
if j != 0:
j = lps[j - 1]
else:
i += 1
return lps
def matrix_mul(self, A, B):
n_rows_a, n_cols_a = len(A), len(A[0])
n_rows_b, n_cols_b = len(B), len(B[0])
# Matrix multiplication not possible
if n_cols_a != n_rows_b:
return None
C = [[0 for _ in range(n_cols_b)] for _ in range(n_rows_a)]
for i in range(n_rows_a):
for j in range(n_cols_b):
for k in range(n_cols_a):
C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % MOD
return C
def matrix_exp(self, A, exponent):
n = len(A)
res = [[0 for _ in range(n)] for _ in range(n)]
# Identity matrix
for i in range(n):
res[i][i] = 1
while exponent:
if exponent & 1:
res = self.matrix_mul(res, A)
exponent >>= 1
A = self.matrix_mul(A, A)
return res
``` | 0 | 0 | ['Java', 'Python3'] | 0 |
string-transformation | ◈ Python ◈ String Matching ◈ Math ◈ DP ◈ KMP | python-string-matching-math-dp-kmp-by-zu-p2hl | Glossary:
s: The original string.
t: The target string to transform s into.
k: The maximum number of allowed rotations.
N: The length of the strings s and t.
MO | zurcalled_suruat | NORMAL | 2025-02-17T19:01:33.125834+00:00 | 2025-02-17T19:01:33.125834+00:00 | 30 | false | ### Glossary:
- $s$: The original string.
- $t$: The target string to transform $s$ into.
- $k$: The maximum number of allowed rotations.
- $N$: The length of the strings $s$ and $t$.
- $MOD$: The modulus for calculations, equal to $10^9 + 7$.
- $dp[i_{turn}][n_{rotation}]$: The number of ways to reach a state of $n_{rotation}$ rotations in the string $s$ after turn $i_{turn}$.
- $dp\_sum[i_{turn}]$: The sum of $\sum_{n_{rotation}=0}^{N-1} dp[i_{turn}][n_{rotation}]$.
- $f\_sum\_gp(a, n, r, MOD)$: Calculates the sum of a geometric progression. Used to efficiently compute the values in the `dp` table. The formula for the sum of a geometric progression is $$S_n = \frac{a(1 - r^n)}{1 - r}, \quad r \ne 1$$
- $S_n$ is the sum of the first $n$ terms of the GP
- $a$ is the first term of the GP
- $r$ is the common ratio of the GP
- $n$ is the number of terms in the GP
- $f\_dp(i_{turn}, n_{rotation}, N, MOD)$: Calculates the value of $dp[i_{turn}][n_{rotation}] \% MOD$.
- $f\_dp\_sum(i_{turn}, N)$: Calculates the value of $dp\_sum[i_{turn}] \% MOD$.
- $f\_mod(x)$: Calculates $x \% MOD$ .
- $PF[i]$: The prefix function, defined as the length of the longest proper prefix of the substring $s[0 \dots i]$ that is also a suffix of this substring.
- $prefix\_function(s)$ Computes the prefix function for a given string s.
- $find\_substring\_indices(s,t)$ function employs the KMP algorithm to identify all occurrences of $t$ within $s + s$. The algorithm constructs a prefix table and uses it to efficiently shift the search window upon encountering mismatches, thereby avoiding redundant comparisons.
### Mathematical Intuition:
The problem involves finding the number of ways to transform a string $s$ into a target string $t$ using a limited number of rotations. The solution utilizes dynamic programming and geometric progression to efficiently count the possible transformations.
The core idea is to represent the number of ways to reach a certain rotation state after at $i_{turn}$ number of turns using a dynamic programming table, denoted as $dp[i_{turn}][n_{rotation}]$. The $dp\_sum[i_{turn}]$ array stores the sum of all possible rotation states for a given turn - $i_{turn}$.
The solution also leverages the Knuth-Morris-Pratt (KMP) algorithm, a linear-time string matching algorithm. The KMP algorithm utilizes a prefix function, denoted as $PF$, to efficiently find occurrences of a pattern (in this case, the target string $t$) within a text (the concatenated string $s + s$). The prefix function $PF[i]$ is defined as the length of the longest proper prefix of the substring $s[0 \dots i]$ that is also a suffix of this substring.
### Derivation of the formulas for $dp[i_{turn}][n_{rotation}]$ and $dp\_sum[i_{turn}]$:
Let $dp[i_{turn}][n_{rotation}]$ be the number of ways to reach a state of $n_{rotation}$ rotations in string $s$ after at the turn - $i_{turn}$.
Let $\large dp\_sum[i_{turn}] = \sum_{n_{rotation}=0}^{N-1} dp[i_{turn}][n_{rotation}]$.
Base case:
$dp\_sum[-1] = 1$
$dp[-1] = 1$
#### Derivation of $dp[i_{turn}][n_{rotation}]$:
$\large dp[i_{turn}][n_{rotation}] = \sum\limits_{\substack{n_{rotation'}=0,\\ n_{rotation'} \ne n_{rotation}}}^{N-1} dp[i_{turn}-1][n_{rotation'}] \\
= \underbrace{(\sum\limits_{\substack{n_{rotation'}=0}}^{N-1} dp[i_{turn}-1][n_{rotation'}] \space)}_{dp\_sum[i_{turn}-1]}- dp[i_{turn}-1][n_{rotation}] \\
= dp\_sum[i_{turn}-1] - dp[i_{turn}-1][n_{rotation}]$
Substituting recursively:
$\large dp[i_{turn}][n_{rotation}] = dp\_sum[i_{turn}-1] - dp[i_{turn}-1][n_{rotation}] \\
= dp\_sum[i_{turn}-1] - (dp\_sum[i_{turn}-2] - dp[i_{turn}-2][n_{rotation}]) \\
= dp\_sum[i_{turn}-1] - dp\_sum[i_{turn}-2] + dp[i_{turn}-2][n_{rotation}] \\
= \dots \\
= \underbrace{(\sum_{k=0}^{i_{turn}} (-1)^{i_{turn}-k} dp\_sum[k-1])}_{\boxed{\large dp\_sum[i_{turn}] = (N-1)^{i_{turn}+1}}}
+ (-1)^{i_{turn}+1} dp[-1][n_{rotation}]$
$\boxed{\large dp[i_{turn}][n_{rotation}] = \sum_{k=0}^{i_{turn}} (-1)^{i_{turn}-k} (N-1)^k + (-1)^{i_{turn}+1} dp[-1][n_{rotation}]} \\
where \space \large dp[-1][n_{rotation}] = \begin{cases} 1, & \text{if } n_{rotation} = 0 \\ 0, & \text{otherwise} \end{cases}$
#### Derivation of $dp\_sum[i_{turn}]$:
$\large dp\_sum[i_{turn}] = \sum\limits_{n_{rotation}=0}^{N-1} dp[i_{turn}][n_{rotation}]\\
= \sum_{n_{rotation}=0}^{N-1} (dp\_sum[i_{turn}-1] - dp[i_{turn}-1][n_{rotation}])\\
= N \cdot dp\_sum[i_{turn}-1] - \sum_{n_{rotation}=0}^{N-1} dp[i_{turn}-1][n_{rotation}]\\
= N \cdot dp\_sum[i_{turn}-1] - dp\_sum[i_{turn}-1]\\
= (N - 1) \cdot dp\_sum[i_{turn}-1]$
Using the base case $\large dp\_sum[-1] = 1$, we get:
$\boxed{\large dp\_sum[i_{turn}] = (N - 1)^{i_{turn}+1}}$
#### KMP prefix function algorithm:
Please refer [this](https://cp-algorithms.com/string/prefix-function.html#efficient-algorithm) article
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
MOD = int(1e9) + 7
# Reference: https://cp-algorithms.com/string/prefix-function.html#implementation
def prefix_function(s):
"""
Computes the KMP prefix function for a given string
Args:
s: The string.
Returns:
The prefix function as a list of integers.
"""
n = len(s)
pi = [0]* n
for i in range(1, n):
j = pi[i-1]
while j > 0 and s[i]!= s[j]:
j = pi[j-1]
if s[i] == s[j]:
j += 1
pi[i] = j
return pi
"""
Reference: https://cp-algorithms.com/string/prefix-function.html#counting-the-number-of-occurrences-of-each-prefix
"""
def find_substring_indices(s, t):
"""
Finds the ending indices of all occurrences of substring t in s.
It is an application of the KMP prefix function.
Args:
s: The string to search in.
t: The substring to search for.
Returns:
A list of indices representing the ending positions of t in s.
"""
n = len(s)
m = len(t)
s2 = t + "#" + s # Concatenate t and s with a special character
pi = prefix_function(s2)
indices = []
for i in range(m + 1, n + m + 1):
if pi[i] == m: # Check if the entire substring t is matched
indices.append(i - m - 1) # Adjust index for concatenation
# print(f"==={s2[m+1:]} , {indices} , {pi[m+1:]}")
return indices
"""
Reference: Asked Gemini to create this utility
"""
def f_sum_gp(a, n, r, MOD = MOD):
"""
Calculates the sum of a geometric progression modulo MOD.
Args:
a: The first term of the geometric progression.
n: The number of terms in the geometric progression.
r: The common ratio of the geometric progression.
MOD: The modulus.
Returns:
The sum of the geometric progression modulo MOD.
"""
# terms = None
if r == 1:
# terms = [a % MOD] * n
result = (a * n) % MOD
else:
# terms = [(a * pow(r, i)) for i in range(n)]
result = (a * (1 - pow(r, n, MOD)) * pow(1 - r, -1, MOD)) % MOD
# print(f"GP ({a, n, r}) = {result} | Terms = {terms}") # Log the sum
return result
"""
"""
def f_dp(i, n_rotation, N, MOD = MOD):
"""
Calculates the value of dp[i][n_rotation] modulo MOD.
Args:
i: The sequence length.
n_rotation: The rotation number.
N: The total number of rotations. It is length of s .
Returns:
The value of dp[i][n_rotation] modulo MOD.
Derivation :
Let rot_optimal be optimal suffix to remove while rotating s to transform s into t
Let rot_1 , rot_2 ... rot_k be the the length of suffix removed while rotating the string at turns 1 ... k
We need to solve for :-
number of possible permutations where sum(rot_1 , rot_2 ... rot_k) % N = rot_optimal
Let dp[i][n_rotation] be the number of ways to reach a state of n_rotation rotations in string s after at the turn - i
Let dp_sum[i] be sum( dp[i][n_rotation] for all 0<=n_rotation<N ) # Eq-1
Base case
dp_sum[-1] = 1
dp[-1][0] = 1
Derivation of Eq-2
dp[i][n_rotation] = sum(
dp[i-1][n_rotation1]
for n_rotation1 in range(N)
if(n_rotation1 != n_rotation) # we cant rotate N times as per P.S.
)
dp[i][n_rotation] = sum(
dp[i-1][n_rotation1]
for n_rotation1 in range(N)
) - dp[i-1][n_rotation]
dp[i][n_rotation] = dp_sum[i-1] - dp[i-1][n_rotation] # Eq-2
Derivation of Eq-3
dp[i][n_rotation] = dp_sum[i-1] - dp[i-1][n_rotation]
dp[i-1][n_rotation] = dp_sum[i-2] - dp[i-2][n_rotation]
...
dp[1][n_rotation] = dp_sum[0] - dp[0][n_rotation]
dp[0][n_rotation] = dp_sum[-1] - dp[-1][n_rotation]
-----------------------------------
dp[i][n_rotation] = (
dp_sum[i-1]
- dp_sum[i-2]
...
(-1 ^ k+1). dp_sum[i-k]
...
(-1 ^ ((i+1)+1)).dp_sum[i - (i+1)] + (-1 ^ (i+1)+1+1).dp[-1][n_rotation]
)
= term_gp + term_const
where
term_gp = sum (
(-1 ^ k+1). dp_sum[i-k]
for k in range(1, i+1 +1)
)
term_const = (-1 ^ (i+1)+1+1).dp[-1][n_rotation]
Now look at term_gp , and replace value of dp_sum[i] = (N-1)^(i+1)
term_gp = sum (
(-1 ^ k+1). ((N-1) ^ (i-k+1))
for k in range(1, i+1 +1)
)
Note that term_gp is a geometric progression with
common factor = (-1).(N-1)
no terms = i+1
first term = (-1 ^ ((i+1)+1))
"""
n_terms = (i +1)
first_term_sign = ((-1) if( (n_terms + 1 )% 2 == 1)else 1)
common_factor = (-1) * (N-1)
term_gp = f_sum_gp( first_term_sign , n_terms , common_factor)
term_const = first_term_sign * (-1) * ( 1 if(n_rotation == 0)else 0 )
res = term_gp + term_const
return res
def f_dp_sum(i, N):
"""
Calculates the value of dp_sum[i] modulo MOD.
Args:
i: The sequence length.
N: The total number of rotations.
Returns:
The value of dp_sum[i] modulo MOD.
Derivation:
Eq-1
dp[i][n_rotation] = dp_sum[i-1] - dp[i-1][n_rotation]
Eq-2
dp_sum[i] = sum(
dp[i][n_rotation1]
for n_rotation1 in range(N)
)
Using Eq-1 and Eq-2
dp_sum[i] = sum(
dp_sum[i-1] - dp[i-1][n_rotation1] # Using Eq-1
for n_rotation1 in range(N)
)
or
dp_sum[i] = (N-1).dp_sum[i-1]
or
dp_sum[i] = (N-1)^(i+1).dp_sum[-1]
or
dp_sum[i] = (N-1)^(i+1) # dp_sum[-1] = 1
"""
return pow(N - 1, i + 1, MOD)
f_mod = lambda x : (x%MOD + MOD)%MOD
class Solution:
def numberOfWays(self, s: str, t: str, k: int) -> int:
N = len(s)
ending_indixes_of_matched_prefixes = find_substring_indices(s+s[:-1],t)
starting_indixes_of_matched_prefixes = [ (i-(N-1)) for i in ending_indixes_of_matched_prefixes]
poss_rotations = [(N-1 -i +1)%N for i in starting_indixes_of_matched_prefixes]
# print(
# "=== {} , {} , {}".format(
# ending_indixes_of_matched_prefixes,
# starting_indixes_of_matched_prefixes,
# poss_rotations
# )
# )
turn = k-1
res = 0
for n_rotation in poss_rotations:
res = f_mod(res + f_dp(turn,n_rotation,N) )
return res
``` | 0 | 0 | ['Math', 'Dynamic Programming', 'String Matching', 'Python3'] | 0 |
string-transformation | Explained Clean Code | 10ms beats 100% | explained-clean-code-10ms-beats-100-by-i-io3n | IntuitionThis problem reduces to finding cyclic patterns in strings and efficiently calculating the number of ways to reach specific positions through k shifts | ivangnilomedov | NORMAL | 2025-02-08T20:17:26.062093+00:00 | 2025-02-08T20:17:26.062093+00:00 | 26 | false | # Intuition
This problem reduces to finding cyclic patterns in strings and efficiently calculating the number of ways to reach specific positions through k shifts using matrix exponentiation.
# Approach
The solution works in three key stages:
1. First, we find if and where string t appears as a cyclic shift of s. This reveals if t can be reached and what positions are possible. We discover an important pattern - if t appears multiple times, s must be a cyclic repetition of a smaller substring (see comment with "abcabc" example in code).
2. For string matching, we use std::string::find which is well-optimized for average cases, though we also include KMP implementation for guaranteed linear time complexity (see string search implementation comments in code).
3. Finally, we transform the problem into calculating how many ways we can make k moves to reach the target position. We use a special diagonal matrix structure that tracks:
- Staying in the same position (diagonal elements)
- Moving to any other position (non-diagonal elements)
(See matrix structure comments in code for details)
Quick matrix exponentiation efficiently computes the result for large k values.
# Complexity
- Time complexity: $$O(L + \log k)$$ where L is string length
# Code
```cpp []
class Solution {
public:
int numberOfWays(const string& s, const string& t, long long k) {
const int L = s.length();
if (t.length() != s.length()) return 0;
// First, we need to find if and where t appears as a cyclic shift of s
// Example: s = "abcabc", t = "cabcab"
// t appears at positions 2 and 5 because:
// - Shifting "abcabc" by 2 positions gives "cabcab" (position 2)
// - Shifting "abcabc" by 5 positions gives "cabcab" (position 5)
//
// When t appears in multiple positions, this reveals an important pattern:
// s must be a cyclic repetition of a smaller substring
// In our example: "abcabc" = "abc" + "abc" (repeated twice)
// This repetition creates regular intervals where t can be found
//
// head_len: first position where t appears (2 in our example)
// period_len: distance between consecutive appearances of t (3 in our example,
// which is the length of the basic repeating unit "abc")
auto [head_len, period_len] = get_head_period(s, t);
if (head_len < 0) return 0; // t is not found as any cyclic shift of s
assert(L % period_len == 0);
int n = L / period_len; // number of complete periods in the string
// The problem reduces to finding how many ways we can make k moves
// to reach position head_len (mod period_len)
// We use a special matrix structure to calculate this efficiently:
// - diagonal elements (d) represent staying in the same position
// - non-diagonal elements (b) represent moving to any other position
DiagMatr trans(n - 1, n, period_len);
DiagMatr ktrans = q_matr_exp(trans, k);
// If head_len = 0 => diagonal element otherwise non-diagonal
return head_len == 0 ? ktrans.d : ktrans.b;
}
private:
static constexpr long long kMod = 1e9 + 7;
// first position where t appears in cyclic shifts of s and the distance to its next appearance
pair<int, int> get_head_period(const string& s, const string& p) {
const int L = s.length();
const int M = 2 * L;
string txt(M, ' ');
copy(s.begin(), s.end(), txt.begin());
copy(s.begin(), s.end(), txt.begin() + L);
{ // Boyer-Moore (std::string::find) performs better on average
int match_pos_1st = txt.find(p);
if (match_pos_1st == string::npos) return { -1, -1 };
int match_pos_2nd = txt.find(p, match_pos_1st + 1);
return { match_pos_1st, match_pos_2nd < 0 ? L : match_pos_2nd - match_pos_1st };
}
// KMP guarantees linear O(N) worst-case but requires pattern preprocessing
vector<int> lsp(L);
for (int i = 1, j = 0; i < L; ++i) {
while (j > 0 && p[j] != p[i])
j = lsp[j - 1];
lsp[i] = j += p[j] == p[i];
}
int match_pos_1st = -1;
int match_pos_2nd = -1;
for (int i = 0, j = 0; i < M; ++i) {
while (j > 0 && p[j] != txt[i])
j = lsp[j - 1];
j += p[j] == txt[i];
if (j == L) {
if (match_pos_1st < 0) {
match_pos_1st = i + 1 - L;
} else {
match_pos_2nd = i + 1 - L;
break;
}
}
}
if (match_pos_1st < 0) return { -1, -1 };
if (match_pos_2nd < 0) return { match_pos_1st, L };
return { match_pos_1st, match_pos_2nd - match_pos_1st };
}
struct DiagMatr {
DiagMatr(long long d, long long b, long long sz) : d(d), b(b), sz(sz) {}
const DiagMatr& operator*=(const DiagMatr& other) {
assert(this->sz == other.sz);
long long a = this->d, B = this->b, c = other.d, D = other.b;
// New diagonal: (current diagonal × other diagonal) + (n-1)(current body × other body)
long long x = (a * c + (sz - 1) * B % kMod * D) % kMod;
// New body: (current diagonal × other body) + (current body × other diagonal) +
// (n-2)(current body × other body)
long long Y = (a * D + c * B + (sz - 2) * B % kMod * D) % kMod;
d = x;
b = Y;
return *this;
}
const DiagMatr& operator=(long long d) {
this->d = d;
this->b = 0;
return *this;
}
long long d = 0; // diagonal elements
long long b = 0; // non-diagonal elements
long long sz = 0; // matrix size
};
template<typename T>
T q_matr_exp(T b, long long p) { // Quick matrix exponentiation
T res(b);
res = 1;
for (; p; p >>= 1) {
if (p & 1)
res *= b;
b *= b;
}
return res;
}
};
``` | 0 | 0 | ['C++'] | 0 |
string-transformation | 💥💥 Beats 100% on runtime and memory [EXPLAINED] | beats-100-on-runtime-and-memory-explaine-08h0 | IntuitionFind how many different ways you can select a subsequence of string t from string s and count the number of ways it can occur for k times, using matrix | r9n | NORMAL | 2025-01-11T08:19:30.683133+00:00 | 2025-01-11T08:19:30.683133+00:00 | 23 | false | # Intuition
Find how many different ways you can select a subsequence of string t from string s and count the number of ways it can occur for k times, using matrix exponentiation and hash functions.
# Approach
I used a rolling hash technique to efficiently compare substrings of s with t, storing the matching positions in a list, then used matrix exponentiation to calculate how many times these matches can occur for k steps.
# Complexity
- Time complexity:
O(n * log(k)), where n is the length of s and k is the power for the matrix exponentiation. The rolling hash is O(n) and matrix exponentiation is O(log(k)).
- Space complexity:
O(n) because we store the hash values and matching indices of string s.
# Code
```csharp []
using System;
using System.Collections.Generic;
public class Solution {
// Modulo constant for large number calculations
const long mod = 1_000_000_007;
public int NumberOfWays(string s, string t, long k) {
// Initialize variables for hash computation
long hash = 0;
long mul = 1; // Power for 26 (for normal hash)
long mul2 = 1; // Power for 27 (for second hash)
long hash2 = 0; // Second hash for string t
long sHash2 = 0; // Second hash for string s
// Compute the hashes for string t
foreach (char c in t) {
// Update powers of 26 and 27 for rolling hash calculation
mul = (mul * 26) % mod;
mul2 = (mul2 * 27) % mod;
// Update hash values for both hash functions
hash = (hash * 26 + (c - 'a')) % mod;
hash2 = (hash2 * 27 + (c - 'a')) % mod;
}
long sHash = 0; // Rolling hash for string s
foreach (char c in s) {
// Update hash values for both hash functions
sHash = (sHash * 26 + (c - 'a')) % mod;
sHash2 = (sHash2 * 27 + (c - 'a')) % mod;
}
// List to store the indices where the hashes of s match t
List<int> index = new List<int>();
int n = s.Length; // Length of string s
// Rolling hash to check all possible substrings of s
for (int i = 0; i < s.Length; ++i) {
// If current substring hash matches target hash, store index
if (sHash == hash && sHash2 == hash2)
index.Add((n - i) % n);
// Update hashes for the next position in the string s
sHash = (sHash * 26) % mod;
sHash2 = (sHash2 * 27) % mod;
// Calculate rolling hash by subtracting the effect of the old character
long other = s[i] - 'a';
long other2 = (other * mul) % mod;
sHash = (sHash + mod - other2 + (s[i] - 'a')) % mod;
other2 = (other * mul2) % mod;
sHash2 = (sHash2 + mod - other2 + (s[i] - 'a')) % mod;
}
long result = 0; // Result variable to store the final count
long[,] root = new long[,] { { 0, n - 1 }, { 1, n - 2 } };
// Matrix exponentiation to compute the final answer
long[,] pow = PowerExp(root, k);
// Calculate the matrix result for the final value of 'a' and 'b'
long a = (pow[0, 0] * 1) % mod;
long b = (pow[1, 0] * 1) % mod;
// Sum the results based on the indices stored
foreach (int num in index) {
result = (result + (num == 0 ? a : b)) % mod;
}
// Return the final result modulo mod
return (int)result;
}
// Helper method to perform matrix exponentiation
private long[,] PowerExp(long[,] mat, long pow) {
var map = new Dictionary<long, long[,]>(); // Cache to store intermediate results
long current = 1;
long[,] val = mat;
long[,] result = new long[mat.GetLength(0), mat.GetLength(0)];
// Initialize result matrix as identity matrix
for (int i = 0; i < mat.GetLength(0); ++i) {
result[i, i] = 1;
}
// Precompute powers of the matrix and store in map
while (current <= pow) {
map[current] = val;
val = MultiplyMat(val, val);
current *= 2;
}
// Use the precomputed powers to perform the matrix exponentiation
while (current > 1) {
current /= 2;
if (pow >= current) {
pow -= current;
result = MultiplyMat(result, map[current]);
}
}
return result;
}
// Helper method to multiply two matrices
private long[,] MultiplyMat(long[,] mat1, long[,] mat2) {
int rows = mat1.GetLength(0); // Number of rows in the first matrix
int cols = mat2.GetLength(1); // Number of columns in the second matrix
long[,] result = new long[rows, cols]; // Initialize result matrix
long sum;
// Matrix multiplication logic
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
sum = 0;
// Perform dot product for each element in the result matrix
for (int k = 0; k < mat1.GetLength(1); ++k) {
sum = (sum + mat1[i, k] * mat2[k, j]) % mod;
}
// Store the result and take modulo
result[i, j] = sum;
}
}
return result;
}
}
``` | 0 | 0 | ['Math', 'String', 'Divide and Conquer', 'Dynamic Programming', 'Recursion', 'Rolling Hash', 'String Matching', 'Matrix', 'C#'] | 0 |
string-transformation | Python Hard | python-hard-by-lucasschnee-3a29 | null | lucasschnee | NORMAL | 2025-01-07T00:31:28.009043+00:00 | 2025-01-07T00:31:28.009043+00:00 | 22 | false | ```python3 []
class Solution:
def numberOfWays(self, s: str, t: str, k: int) -> int:
'''
its just a rotating string
so, first find number of ways that s rotated is t
then, we can make N - 1 moves every turn, and 1 move the last turn
exactly k operations
N - 1 then -1 again if we are currently on
only N - 1 options per turn
then, 1 for last turn
'''
N = len(s)
MOD = 10 ** 9 + 7
total = 0
good_s = 0
def z_function(s):
z, l, r, n = [0] * len(s), 0, 0, len(s)
for i in range(1, n):
if i < r:
z[i] = min(r - i, z[i - l])
while i + z[i] < n and s[i + z[i]] == s[z[i]]:
z[i] += 1
if i + z[i] > r:
l, r = i, i + z[i]
return z
z = z_function(t + "#" + s + s)[len(t)+1:]
for i in range(1, N):
if z[i] >= len(t):
good_s += 1
def mat_mult(A, B):
# Multiply two 2x2 matrices A and B
return [[(A[0][0] * B[0][0] + A[0][1] * B[1][0]) % MOD,
(A[0][0] * B[0][1] + A[0][1] * B[1][1]) % MOD],
[(A[1][0] * B[0][0] + A[1][1] * B[1][0]) % MOD,
(A[1][0] * B[0][1] + A[1][1] * B[1][1]) % MOD]]
def mat_expo(M, exp):
# Exponentiate matrix M to the power exp
res = [[1, 0], [0, 1]] # Identity matrix
while exp > 0:
if exp % 2 == 1:
res = mat_mult(res, M)
M = mat_mult(M, M)
exp //= 2
return res
# Base transition matrix
M = [[N - 2, N - 1],
[1, 0]]
dp = [0] * 2
dp[0] = good_s
if s == t:
dp[1] = 1
# for _ in range(k):
# nxt_dp = [0] * 2
# nxt_dp[0] += dp[1] * (N-1)
# nxt_dp[0] += dp[0] * (N - 2)
# nxt_dp[1] += dp[0]
# nxt_dp[0] %= MOD
# nxt_dp[1] %= MOD
# dp = nxt_dp
# Compute M^k
M_k = mat_expo(M, k)
result = (M_k[1][0] * dp[0] + M_k[1][1] * dp[1]) % MOD
return result
# return dp[1]
``` | 0 | 0 | ['Python3'] | 0 |
string-transformation | String Matching + Maths | string-matching-maths-by-up41guy-k2lo | TC: O(N + logK)
SC : O(N) | Cx1z0 | NORMAL | 2024-12-26T11:24:27.374397+00:00 | 2024-12-26T11:30:03.732484+00:00 | 25 | false | TC: O(N + logK)
SC : O(N)
---
```javascript []
function numberOfWays(s, t, k) {
const MOD = 1e9 + 7;
const n = s.length;
if (!s || !t || k < 0) return 0;
// Create circular string once
const ss = s + s;
const first = ss.indexOf(t);
if (first === -1) return 0;
const zero_targets = first === 0 ? 1 : 0;
const period = ss.slice(1).indexOf(s) + 1;
const frequency = Math.floor(n / period);
const nonzero_targets = frequency - zero_targets;
const binPow = (a, b, mod) => {
let result = 1n;
a = BigInt(a);
b = BigInt(b);
mod = BigInt(mod);
while (b > 0n) {
if (b & 1n) {
result = (result * a) % mod;
}
a = (a * a) % mod;
b >>= 1n;
}
return Number(result);
};
const modN = MOD * n;
const power = binPow(n - 1, k, modN);
const sign = k % 2 === 0 ? 1 : -1;
const ways_0 = Math.floor((power + (n - 1) * sign) / n);
const ways_1 = Math.floor((power - sign) / n);
return ((zero_targets * ways_0 + nonzero_targets * ways_1) % MOD + MOD) % MOD;
}
``` | 0 | 0 | ['Math', 'String', 'String Matching', 'JavaScript'] | 0 |
string-transformation | 7ms Python solution (top 5%) with extensive comments and explanation behind the mathematics | 7ms-python-solution-top-5-with-extensive-fv6u | Intuition\n Describe your first thoughts on how to solve this problem. \nIn general, you can see the source string $s$ and target string $t$ as two circular str | NicolasHeintz | NORMAL | 2024-11-26T18:48:48.327579+00:00 | 2024-11-26T18:48:48.327614+00:00 | 27 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIn general, you can see the source string $s$ and target string $t$ as two circular strings. The only possible transformation is a rotation of that string. At each operation, you can rotate the string with any amount $[1,L-1]$, with $L$ the length of $s$. The null operations of not rotating the string or doing a full rotation, are not allowed. \n\nThe string \'circle\' can be in as many positions as the length of the string $L$. In my explanation, I will make a distinction between 3 kinds of positions: \n- The start position: The position in which the string $s$ starts\n- A match position: A position where $s = t$\n- A mismatch position: A position where $s \\neq t$\n\nWe can split the main problem in 4 subproblems:\n- Is there a valid match between $s$ and $t$?\n- If yes, is there more than a single match possible?\n- In how many ways can we go from the start position to each possible position **before** the last operation?\n- In how many ways can we go from each position to a match position **during** the last operation?\n\nI will cover each subproblem 1 by 1 in the Approach section. Feel free to skip to the part(s) you struggle with. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nI solve each of the subproblems one by one. \n\n**Is there a valid match between s and t?**\nOne of the simplest ways to check this is to double $s$ (`s+s`) and check whether $t$ is in $s$. That way, you can quickly check whether `t = s[i:]+s[:i]` for any rotation $i$ without constantly making new strings (which is costly), as `s[i:]+s[:i] = doubleS[i:L+i]`, with $L$ the length of $s$. This is especially fast in Python, as you avoid expensive Python loops. \n\n**Is there more than a single match possible?**\nThis can be checked with a very similar method as the first problem: double $s$ and then find the first $0<i<L$ where `doubleS[i:L+i] == s`. In other words: is $s$ equal to another $s$ rotated with i positions. If yes, this means that s consists of a little subpattern of length i. In Python, you can quickly find the first match with ```string.find(s,1,-1)```. The 1 and -1 say that the trivial matches of $s$ with $doubleS$ at the start and end of $doubleS$ don\'t count. \n\nExample:\n\'abab\' has subpattern \'ab\' of length 2, because the first \'abab\' you can find in \'abababab\' (apart from the start), starts at index 2. \n\n**In how many ways can we go from the start position to each possible position before the last operation?**\nThis is the hardest part of the problem. Intuitively, you might want to solve this with a naive recursive program. However, the total number of operations can get massive (up to 10^15). So any kind of recursive loop is out of the question. Instead, we can use mathematics. For now, we don\'t really care whether a position matches $t$ or not, as this is only important for the last operation. We only want to know in how many ways you can reach each possible position after a specific amount of operations.\n\nA first realisation is that there is a massive amount of symmetry. In fact, there are really only two different kinds of positions: \n- the start position (there is only 1 of them)\n- the non-start positions (there are L-1 of them)\nAfter the first operation, you can be at any non-start position but not at the start position. After the second operation, you can go from any non-start position to any of the L-2 other non-start positions, or back to the start position. Since there is no difference in which non-start positions can be reached from other positions, the number of ways to go to a non-start position will thus be equal for all non-start positions. \n\nLet\'s call the number of ways you can reach the start position at iteration $i$ $a_i$ and the number of ways to reach a single of the non-start positions $b_i$. We can then compute $a_{i+1}, b_{i+1}$:\n\n$$\\begin{bmatrix}\na_{i+1}\\\\\nb_{i+1}\n\\end{bmatrix}\n=\n\\begin{bmatrix}\n0 & L-1\\\\\n1 & L-2\n\\end{bmatrix}\n\\begin{bmatrix}\na_{i}\\\\\nb_{i}\n\\end{bmatrix}\n$$.\n$a_{i+1}=(L-1)b_i$, since all $L-1$ non-start positions $b_i$ can go to the start position after the next operation. Similarly, $b_{i+1}=a_i+(L-2)b_i$ because you can reach a non-start position $b_{i+1}$ from the start position $a_i$ and any non-start position different from itself in a single operation.\n\nWe start with $\\begin{bmatrix}\na_{0}\\\\\nb_{0}\n\\end{bmatrix} \n=\n\\begin{bmatrix}\n1\\\\\n0\n\\end{bmatrix} \n$, and want to compute $\\begin{bmatrix}\na_{k-1}\\\\\nb_{k-1}\n\\end{bmatrix}=A^{k-1}\\begin{bmatrix}\na_{0}\\\\\nb_{0}\n\\end{bmatrix}$ as fast as possible ($k-1$ because we only go up to the penultimate operation). This is possible by doing an eigenvalue decomposition on $A = V\\Lambda V^{-1}$ and then computing $A^k = V\\Lambda^kV^{-1}$, with $V$ the eigenvectors and $\\Lambda$ a diagional matrix with the eigenvalues. Because $\\Lambda$ is diagonal, $\\Lambda^{k-1} = \n\\begin{bmatrix}\n\\lambda_1^{k-1} & 0\\\\\n0 & \\lambda_2^{k-1}\n\\end{bmatrix}$, with $\\lambda_{1,2}$ the eigenvalues.\n\nIf we apply this on the problem at hand and do some algebra (ask chatGPT/... if you\'re not familiar), we get: \n$$\nV = \n\\begin{bmatrix}\n1 & 1-L\\\\\n1 & 1\n\\end{bmatrix},\\ \\Lambda = \n\\begin{bmatrix}\nL-1 & 0\\\\\n0 & -1\n\\end{bmatrix},\\ V^{-1}=1/L\n\\begin{bmatrix}\n1 & L-1\\\\\n-1 & 1\n\\end{bmatrix}.\n$$\nWe can further compute \n$A^{k-1}\\begin{bmatrix}\na_{0}\\\\\nb_{0}\n\\end{bmatrix}=1/L\n\\begin{bmatrix}\n(L-1)^{k-1}+(-1)^{k-1}(L-1)\\\\\n(L-1)^{k-1}-(-1)^{k-1}\n\\end{bmatrix}$.\n\nSo we now have a straightforward road to the solution of this subproblem, or do we?\n\nRemember that $k$ can be massive. So $(L-1)^{k-1}$ will quickly overflow. Luckily Python can compute the modulo of the power directly with `pow(L-1,k-1,M)`, with M the modulo constant. pow uses something similar to the exponentiation by squaring method. $(-1)^{k-1}$ is simply 1 if $k$ is uneven and -1 otherwise. I wasn\'t sure whether pow checks for 1/-1 before computing the power, so I did it myself. However, once you take the module, you cannot simply divide by $L$. Instead, you need to multiply with `Linv = pow(L,M-2,M)`, following Fermat\'s little theorem. Just dividing by L only introduces relatively small mistakes, so you probably could get away with rounding the result in this exercise. But it will break in some edge cases. Since computing Linv is pretty expensive, I only do it if I think it is likely that a modulo was taken.\n\n**In how many ways can we go from each position to a match position during the last operation?**\nThis one is quite tame compared to the previous problem. It depends on whether the start position of s already matches t. We further introduce $N$ as the total number of possible matches (found in question 2, as $L/i$ with $i$ the length of a matching substring)\n- if the start position is a match position: You can reach $(N-1)$ match positions from the single start position, $N$ match positions from the $L-N$ mismatch positions (none of which is a start position) and $N-1$ match positions from the other $N-1$ non-start match positions. So the total amount of ways to reach a start position is:\n$T = a_{k-1}(N-1)+b_{k-1}N(L-N) + b_{k-1}(N-1)(N-1)$.\n- if the start position is a mismatch position: You can reach $N$ match positions from the single start position, $N$ match positions from the $L-N-1$ non-start mismatch positions (exclude the start position) and $N-1$ match positions from the $N$ match positions (none of which is the start position). So the total amount of ways to reach a start position is:\n$T = a_{k-1}N+b_{k-1}N(L-N-1) + b_{k-1}N(N-1)$.\n\nThen take one final time the modulo `T = T % M` and we are done.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$O(n) + O(log(k-1 \\text{ mod } M))$ (we do very little with the strings themselves, only checking if a valid answer exists and checking for repeating patterns. At high $k$, computing the power is by far the most expensive step, with $k = aM, a \\in \\mathcal{N}_0$ the worst case scenario.)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$O(n)$. The most expensive part by far is doubling s. Steps 3 and 4 barely require any memory.\n\nAs I\'m a mathematical engineer that is still learning how to code properly myself, I cannot guarantee that there are no blatant suboptimalities in my code. If you notice any methods that are suboptimal/... please let me know!\n# Code\n```python3 []\nfrom math import sqrt\n\nclass Solution:\n def numberOfWays(self, s: str, t: str, k: int) -> int:\n # Init \n L = len(s)\n modPower = 9 \n modConstant = 10**modPower+7 # The constant to do modulo operations with\n doubleS = s+s # concatenation of 2 s\'s\n\n # Check if there is a solution\n possibleSolution = t in doubleS \n \n # Early quitting: no solution is possible\n if not possibleSolution:\n return 0\n\n # Check whether you are already at the solution\n startAtSolution = s == t\n \n # Check if string consists of substrings\n # Idea: finds the first place where s matches doubleS, apart from the start. \n # If such a match is found, that means that s consists of substrings. Length of the substring = index where match is found\n subStringLen = doubleS.find(s,1,-1) \n if subStringLen == -1:\n nWaysToFinish = 1\n else:\n nWaysToFinish = L//subStringLen\n \n # Amount of turns where you can do whatever you want\n nFreeTurns = max(k-1,0)\n nFreeTurnsOdd = nFreeTurns & 1 # Check if the number is odd\n\n # Compute the amount of ways you can reach each position in the penultimate round\n\n # Memoisation of expensive computations (L-1)^nFreeTurns mod modConstant\n intermediatex = pow((L-1), nFreeTurns, modConstant)\n\n # Necessary to divide by L after taking a modulo. Since it is rather expensive, only do it if it is likely that a modulo was necessary\n moduloLikely = (len(str(L-1))+1)*nFreeTurns > modPower\n\n if moduloLikely:\n # Use the expensive computation of 1/L with modulo\n Linv = pow(L,modConstant-2,modConstant)\n xLast = [(intermediatex + (L-1)*(-1)**nFreeTurnsOdd)*Linv, (intermediatex-(-1)**nFreeTurnsOdd)*Linv]\n else:\n # No modulo taken yet. So can just divide by L \n xLast = [(intermediatex + (L-1)*(-1)**nFreeTurnsOdd)//L, (intermediatex-(-1)**nFreeTurnsOdd)//L]\n\n # Compute the amount of ways to go from the last state to the solution\n if startAtSolution:\n # start position is (one of) the solution(s).\n return (xLast[0]*(nWaysToFinish-1) + # amount of ways to go from start position to a solution\n xLast[1]*(L-nWaysToFinish)*nWaysToFinish + # amount of ways to go from position that is not a solution to a solution\n xLast[1]*(nWaysToFinish-1)*(nWaysToFinish-1)) % modConstant # amount of ways to go from a solution position different than the start position to a solution\n \n else:\n # start position is not a solution\n return (xLast[0]*nWaysToFinish + \n xLast[1]*(L-nWaysToFinish-1)*nWaysToFinish + # Go from a position that is not the solution or start position to a solution\n xLast[1]*nWaysToFinish*(nWaysToFinish-1)) % modConstant # Go from a solution to another solution\n\n # (0,1), (L-1,L-2), ((L-2)^2+(L-2),(L-2)^2+(L-1))\n # a(i) = (L-1)*b(i-1)\n # b(i) = (L-2)*b(i-1)+a(i-1)\n # A = [ 0 L-1\n # 1 L-2]\n\n\n \n``` | 0 | 0 | ['Math', 'Dynamic Programming', 'Python', 'Python3'] | 0 |
string-transformation | java + KMP | java-kmp-by-liuheng0213-mx1u | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | liuheng0213 | NORMAL | 2024-08-18T00:41:43.530836+00:00 | 2024-08-18T00:41:43.530871+00:00 | 32 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n Long mod = 1000000007L;\n public int numberOfWays(String s, String t, long k) {\n int n = s.length();\n\n String twoS = s+s;\n\n String newS =twoS.substring(0,2* n - 1);\n\n\n int p = kmpNum(newS,t);\n int f = s.equals(t) ? 0: 1;\n int g = s.equals(t)? 1: 0;\n\n long[] matrix = new long[]{n-p-1,n-p,p,p-1};\n long[] matrixRes= calculate(matrix,k);\n return (int)(matrixRes[2] * (long)f%mod) + (int)(matrixRes[3]* (long)g%mod);\n }\n\n private long[] calculate(long[] matrix, long k) {\n if(k == 0){\n return new long[]{1,0,0,1};\n }\n if(k == 1){\n return matrix;\n }\n\n long[] a = calculate(matrix,k/2);\n\n if(k % 2 == 0){\n return muliply(a,a);\n }else{\n return muliply(muliply(a,a),matrix);\n }\n }\n\n private long[] muliply(long[] a, long[] b) {\n return new long[]{(a[0] * b[0])%mod+ (a[1] * b[2])%mod , (a[0] * b[1])%mod + (a[1]* b[3])%mod ,(a[2] * b[0])%mod+ (a[3]*b[2])%mod ,(a[2] * b[1])%mod + (a[3]*b[3])%mod};\n }\n\n\n public int kmpNum(String str, String pat) {\n int n =str.length();\n\n //dp[i] means the string ends with index i in the str has how many matching letters with pat\n int[] dp = new int[n];\n\n int res = 0;\n dp[0] = str.charAt(0) == pat.charAt(0) ? 1: 0;\n\n if(dp[0] == 1 && pat.length() ==1){\n res++;\n }\n int[] next = getNext(pat);\n for(int i = 1;i< n;i++){\n int j = dp[i - 1];\n\n while(j> 0 && (j == pat.length() ||str.charAt(i) != pat.charAt(j))){\n j = next[j - 1];\n }\n dp[i] = j< pat.length() && str.charAt(i) == pat.charAt(j)? j+1 : j;\n\n if(dp[i] == pat.length()){\n res++;\n }\n }\n\n return res;\n\n }\n\n\n private int[] getNext(String s) {\n int n = s.length();\n int[] next = new int[n];\n int i = 1, j = 0;\n while (i < n) {\n if (s.charAt(i) == s.charAt(j)) {\n j++;\n next[i++] = j;\n } else if (j > 0) {\n j = next[j - 1];\n } else {\n i++;\n }\n }\n return next;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
string-transformation | Simple Math||100% tc and sc beat ||O(n) solution | simple-math100-tc-and-sc-beat-on-solutio-ltyh | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Sdas_1905 | NORMAL | 2024-07-06T09:28:44.207301+00:00 | 2024-07-06T09:28:44.207334+00:00 | 83 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\nconst long long MOD = 1000000007;\n bool isRotation(const string& s, const string& t) {\n if (s.length() != t.length()) {\n return false;\n }\n \n string concatenated = t + t;\n \n return concatenated.find(s) != string::npos;\n}\nlong long modExp(long long base, long long exp, long long mod) {\n long long result = 1;\n while (exp > 0) {\n if (exp % 2 == 1) {\n result = (result * base) % mod;\n }\n base = (base * base) % mod;\n exp = exp / 2;\n }\n return result;\n}\n\nlong long nthTerm(long long n , long long len) {\n long long power_len_n = modExp(len-1, n, MOD);\n long long power_minus1_n = (n % 2 == 0) ? 1 : MOD - 1; \n long long term = (power_len_n - power_minus1_n + MOD) % MOD; \n term = (term * modExp(len, MOD - 2, MOD)) % MOD; \n \n return term;\n}\nvector<int> KMP(string& s) {\n int n = s.length();\n std::vector<int> pi(n, 0);\n int k = 0;\n \n for (int i = 1; i < n; ++i) {\n while (k > 0 && s[i] != s[k]) {\n k = pi[k - 1];\n }\n if (s[i] == s[k]) {\n ++k;\n }\n pi[i] = k;\n }\n \n return pi;\n}\n\nint numberOfRepetitions(string& s) {\n int n = s.length();\n std::vector<int> pi = KMP(s);\n int l = pi[n - 1]; \n \n if (l > 0 && n % (n - l) == 0) {\n return n / (n - l);\n }\n \n return 1;\n}\nbool issame(string t,string s){\n for(int i =0;i<t.length();i++){\n if(s[i]!=t[i])\n return false;\n }\n return true;\n}\n int numberOfWays(string s, string t, long long k) {\n if(!isRotation(s,t))\n return 0;\n int len = s.length();\n int rep = numberOfRepetitions(s);\n long long power_minus1_n = (k % 2 == 0) ? 1 : - 1;\n if(!issame(s,t)){\n power_minus1_n =0;\n }\n return (int)(((long long)rep*nthTerm(k,len))%MOD + power_minus1_n) ;\n }\n};\n``` | 0 | 1 | ['Math', 'C++'] | 0 |
string-transformation | String Transformation || Python 3 || Easy | string-transformation-python-3-easy-by-u-u5iq | Intuition\n Describe your first thoughts on how to solve this problem. \n\nThe problem requires transforming string s into string t through a series of cyclic o | user4609eh | NORMAL | 2024-05-23T14:05:00.463181+00:00 | 2024-05-23T14:05:00.463213+00:00 | 103 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThe problem requires transforming string s into string t through a series of cyclic operations. The key intuition is to recognize the **cyclic nature of the transformation** and efficiently **count the number of valid transformations using modular arithmetic**.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nCount Character Frequencies: Use a counter to count the frequency of each character in s to handle special cases where s consists of repeated characters.\nFind Initial Match: Check if t can be found as a substring in the concatenated string s+s. If not found, return 0 since transformation is impossible.\nSpecial Cases Handling:\nIf s consists of a single unique character, the problem reduces to counting ways based on length modulo operations.\nFor two unique characters, handle the alternating patterns.\nCalculate Valid Transformations:\nFor general cases, count valid cyclic shifts that match t using a sliding window over s+s.\nUse modular exponentiation to handle large k values efficiently.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\nTime Complexity: **O(n^2)** for concatenating the string and finding all possible cyclic permutations.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\nSpace Complexity: **O(n)**, for storing intermediate results and counters.\n\n# Code\n```\nclass Solution:\n def numberOfWays(self, s: str, t: str, k: int) -> int:\n M = 10 ** 9 + 7\n cnt = Counter(s)\n n = len(s)\n i = (s + s).find(t)\n if i == -1:\n return 0\n if len(cnt) == 1:\n return pow(n - 1, k, M) % M\n elif len(cnt) == 2:\n if s == s[:2] * (n // 2):\n res = n // 2\n if s == t:\n curr = pow(n - 1, k, M) * res\n if k & 1:\n curr -= n - res\n else:\n curr += n - res\n return curr * pow(n, -1, M) % M\n else:\n curr = pow(n - 1, k, M) * res\n if k & 1:\n curr += res\n else:\n curr -= res\n return curr * pow(n, -1, M) % M\n \n\n\n ss = s[i+1:] + s\n res = 1\n while len(ss) > n:\n i = ss.find(t)\n if i == -1:\n break\n if i <= len(ss) - n - 1:\n res += 1\n ss = ss[i+1:]\n \n if s == t:\n curr = pow(n - 1, k, M) * res\n if k & 1:\n curr -= n - res\n else:\n curr += n - res\n return curr * pow(n, -1, M) % M\n else:\n curr = pow(n - 1, k, M) * res\n if k & 1:\n curr += res\n else:\n curr -= res\n return curr * pow(n, -1, M) % M\n``` | 0 | 0 | ['Python3'] | 0 |
string-transformation | Simple Solution - Rolling Hash + Observation | simple-solution-rolling-hash-observation-iwum | While this problem can be solved in multiple ways, I wanted to share my solution which only uses rolling hashes, binary exponentiation + Fermat\'s Little Theore | sternentaucher | NORMAL | 2023-11-07T00:30:46.202694+00:00 | 2023-11-07T00:30:46.202727+00:00 | 71 | false | While this problem can be solved in multiple ways, I wanted to share my solution which only uses rolling hashes, binary exponentiation + Fermat\'s Little Theorem.\n\nFirst oberservation is that the relative order of elements does not change. Therefore, after an operation, we either end at the 0th, 1st, 2nd, ..., (n-1)th character. In total, we have `n` possible orderings. Now, for each ordering, we can only go into those orderings that don\'t end with the current end character. Thus, the branching factor of the operations tree is $n-1$. After $l$ operations we in total $(n-1)^l$ operations. After playing around with small examples, we find that the number of orderings after $l$ operations only differ by +/- 1 which yields to a closed formula which derivation can be found in other posts.\n\n# Code\n```\n#include <vector>\n#include <iostream>\n\nusing namespace std;\nconst int MOD = 1\'000\'000\'007;\nconst int MOD2 = 31;\nclass Solution {\npublic:\n \n vector<long long> sHashes;\n long long tHash = 0;\n\n vector<long long> pows;\n vector<long long> ipows;\n\n long long binpow(long long base, long long exp) {\n long long r = 1;\n while (exp) {\n if (exp & 1) {\n r = r * base;\n r %= MOD;\n }\n base = base * base;\n base %= MOD;\n exp >>= 1;\n }\n return r;\n }\n\n long long inv(long long num) {\n return binpow(num, MOD-2);\n }\n\n // Check in O(1) if appending suffix of size len of s to front yields t\n bool checkSame(string& s, string& t, int len) {\n const int n = s.size();\n if (len == 0) {\n return tHash == sHashes[n-1];\n }\n long long nHash = (sHashes[n-1-len] * pows[len]) % MOD;\n long long subHash = (sHashes[n-1] - (n-1-len < 0 ? 0 : sHashes[n-1-len]) + MOD) % MOD;\n subHash = (subHash * ipows[n-1-len+1]) % MOD;\n nHash = (nHash + subHash) % MOD;\n return nHash == tHash;\n }\n \n int numberOfWays(string s, string t, long long k) {\n const int n = s.size();\n \n // Precalculate powers\n pows.resize(n);\n ipows.resize(n);\n for(int i = 0; i < n; ++i) {\n pows[i] = binpow(MOD2, i);\n ipows[i] = inv(pows[i]);\n }\n \n // Calculate rolling hashes of s & t\n sHashes.resize(n);\n sHashes[0] = s[0] - \'a\' + 1;\n tHash = t[0] - \'a\' + 1;\n for (int i = 1; i < n; ++i) {\n sHashes[i] = (sHashes[i-1] + (s[i] - \'a\' + 1) * pows[i]) % MOD;\n tHash = (tHash + (t[i] - \'a\' + 1) * pows[i]) % MOD;\n }\n \n long long x = 0;\n if (k % 2 == 0) {\n x = (binpow(n-1, k) - 1 + MOD) % MOD;\n x = (x * inv(n)) % MOD;\n } else {\n x = (binpow(n-1, k) + 1) % MOD;\n x = (x * inv(n)) % MOD;\n }\n \n vector<int> dp(n,0);\n for (int i = 0; i < n; ++i) {\n if (k % 2 == 0) {\n dp[i] = i == 0 ? x + 1 : x;\n } else {\n dp[i] = i == 0 ? (x - 1 + MOD) % MOD : x;\n }\n }\n\n long long answer = 0;\n for (int i = 0; i < n; ++i) {\n if (checkSame(s, t, i)) {\n answer = (answer + dp[i]) % MOD;\n }\n }\n\n return answer;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
string-transformation | C++ solution | c-solution-by-pejmantheory-9r2t | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | pejmantheory | NORMAL | 2023-11-01T09:45:52.106538+00:00 | 2023-11-01T09:45:52.106555+00:00 | 78 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public:\n // This dynamic programming table dp[k][i] represents the number of ways to\n // rearrange the string s after k steps such that it starts with s[i].\n // A string can be rotated from 1 to n - 1 times. The transition rule is\n // dp[k][i] = sum(dp[k - 1][j]) for all j != i. For example, when n = 4 and\n // k = 3, the table looks like this:\n //\n // -----------------------------------------------------------\n // | | i = 0 | i = 1 | i = 2 | i = 3 | sum = (n - 1)^k |\n // -----------------------------------------------------------\n // | k = 0 | 1 | 0 | 0 | 0 | 1 |\n // | k = 1 | 0 | 1 | 1 | 1 | 3 |\n // | k = 2 | 3 | 2 | 2 | 2 | 9 |\n // | k = 3 | 6 | 7 | 7 | 7 | 27 |\n // -----------------------------------------------------------\n //\n // By observation, we have\n // * dp[k][!0] = ((n - 1)^k - (-1)^k) / n\n // * dp[k][0] = dp[k][!0] + (-1)^k\n int numberOfWays(string s, string t, long long k) {\n const int n = s.length();\n const int negOnePowK = (k % 2 == 0 ? 1 : -1); // (-1)^k\n const vector<int> z = zFunction(s + t + t);\n const vector<int> indices = getIndices(z, n);\n vector<int> dp(2); // dp[0] := dp[k][0]; dp[1] := dp[k][!0]\n dp[1] = (modPow(n - 1, k) - negOnePowK + kMod) % kMod *\n modPow(n, kMod - 2) % kMod;\n dp[0] = (dp[1] + negOnePowK + kMod) % kMod;\n return accumulate(indices.begin(), indices.end(), 0LL,\n [&](long long subtotal, int index) {\n return (subtotal + dp[index == 0 ? 0 : 1]) % kMod;\n });\n }\n\n private:\n static constexpr int kMod = 1\'000\'000\'007;\n\n long modPow(long x, long n) {\n if (n == 0)\n return 1;\n if (n & 1)\n return x * modPow(x, n - 1) % kMod;\n return modPow(x * x % kMod, n / 2);\n }\n\n // https://cp-algorithms.com/string/z-function.html#implementation\n vector<int> zFunction(const string& s) {\n const int n = s.length();\n vector<int> z(n);\n int l = 0;\n int r = 0;\n for (int i = 1; i < n; ++i) {\n if (i < r)\n z[i] = min(r - i, z[i - l]);\n while (i + z[i] < n && s[z[i]] == s[i + z[i]])\n ++z[i];\n if (i + z[i] > r) {\n l = i;\n r = i + z[i];\n }\n }\n return z;\n }\n\n // Returns the indices in the string `s` such that for each `i` in the\n // returned indices, `s[i:] + s[:i] = t`.\n vector<int> getIndices(const vector<int>& z, int n) {\n vector<int> indices;\n for (int i = n; i < n + n; ++i)\n if (z[i] >= n)\n indices.push_back(i - n);\n return indices;\n }\n};\n\n``` | 0 | 0 | ['C++'] | 0 |
string-transformation | Python || Dynamic Programming | python-dynamic-programming-by-abhinav_51-lwgr | Intuition\nThe code aims to compute the number of ways to rearrange the string s after k rotations such that it equals string t. The core intuition is to utiliz | Abhinav_5136 | NORMAL | 2023-10-30T13:53:32.330232+00:00 | 2023-10-30T13:54:41.572763+00:00 | 265 | false | # Intuition\nThe code aims to compute the number of ways to rearrange the string s after k rotations such that it equals string t. The core intuition is to utilize the properties of rotating strings and mathematical deductions to derive a dynamic programming transition, reducing the problem complexity.\n\n# Approach - Dynamic Programming with Mathematical Deduction and Z-Function\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution:\n def numberOfWays(self, s: str, t: str, k: int) -> int:\n kMod = 1_000_000_007\n n = len(s)\n negOnePowK = 1 if k % 2 == 0 else -1\n z = self._zFunction(s + t + t)\n indices = [i - n for i in range(n, n + n) if z[i] >= n]\n dp = [0] * 2\n dp[1] = (pow(n - 1, k, kMod) - negOnePowK) * pow(n, kMod - 2, kMod)\n dp[0] = dp[1] + negOnePowK\n return sum(dp[0] if index == 0 else dp[1] for index in indices) % kMod\n\n def _zFunction(self, s: str) -> List[int]:\n n = len(s)\n z = [0] * n\n l = 0\n r = 0\n for i in range(1, n):\n if i < r:\n z[i] = min(r - i, z[i - l])\n while i + z[i] < n and s[z[i]] == s[i + z[i]]:\n z[i] += 1\n if i + z[i] > r:\n l = i\n r = i + z[i]\n return z\n``` | 0 | 0 | ['Dynamic Programming', 'Python3'] | 0 |
string-transformation | [Python] Easy Solution for Difficult Problem | String Hashing + Maths | python-easy-solution-for-difficult-probl-ewed | Intuition\n Describe your first thoughts on how to solve this problem. \nReally good problem, one needs to know various advance concepts to solve this problem.\ | tr1ten | NORMAL | 2023-10-24T05:20:09.744017+00:00 | 2023-10-24T05:20:09.744036+00:00 | 125 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nReally good problem, one needs to know various advance concepts to solve this problem.\n\nRealizations:\n1. t is just some rotation of s\n2. Now question reduces to finding number of ways to do such rotation in exactly k steps\n3. There only n unique rotations (0 to n-1) and there might be case where t can be formed using more than one rotation. \n \n# Approach\n<!-- Describe your approach to solving the problem. -->\nmathematically each step will cause some rotation thus we can write\n(x1 + x2 + x3 ... + xk)%n = r1\n\nNow we can use dp to find number of ways but that would cause tle since k is large thus either we use matrix exponentiation or try to find suitable formula.\n\nHint: try expanding dp recurrence and find AGP\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n + logK)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code\n```\ndef fast_pow(a, b, m):\n if b == 0:\n return 1\n if b == 1:\n return a % m\n if b % 2 == 0:\n return fast_pow(a * a % m, b // 2, m)\n else:\n return a * fast_pow(a * a % m, b // 2, m) % m\nM = 2**61 - 1;\nB = 9973\ndef code(x): return ord(x) - ord(\'a\') + 1\nclass HashedString:\n def __init__(self,s) -> None:\n n = len(s)\n self.ppow = [1]\n self.hashes = [0]\n for i in range(n): self.ppow.append((self.ppow[-1]*B)%M)\n for i in range(n): self.hashes.append((self.hashes[-1]*B + code(s[i]))%M)\n def get_hash(self,i,j):\n return (self.hashes[j+1]-self.hashes[i]*self.ppow[j-i+1])%M\n \n\nclass Solution:\n def numberOfWays(self, s: str, t: str, k: int) -> int:\n S = HashedString(s+s)\n T = HashedString(t)\n mod = 10**9 + 7\n nn = len(t)-1\n dp = [0,1]\n if k>1:\n inv = fast_pow(nn+1,mod-2,mod)\n dp[0] = (fast_pow(nn,k,mod) + (1 if k%2==0 else -1)*nn)%mod\n dp[1] = (dp[0]+( (-1 if k%2==0 else 1)*(nn+1)) +mod)%mod\n dp[0] = (dp[0]*inv)%mod\n dp[1] = (dp[1]*inv)%mod\n ans = 0\n for i in range(len(s)):\n if S.get_hash(i,i+len(t)-1)==T.get_hash(0,len(t)-1):\n ans = (ans+dp[i>0])%mod\n return ans\n``` | 0 | 0 | ['Python3'] | 0 |
string-transformation | Just a runnable solution | just-a-runnable-solution-by-ssrlive-qxfc | \nimpl Solution {\n const M: i64 = 1_000_000_007;\n\n fn add(x: i64, y: i64) -> i64 {\n if (x + y) >= Solution::M {\n x + y - Solution:: | ssrlive | NORMAL | 2023-10-18T09:37:15.216996+00:00 | 2023-10-18T09:37:15.217014+00:00 | 18 | false | ```\nimpl Solution {\n const M: i64 = 1_000_000_007;\n\n fn add(x: i64, y: i64) -> i64 {\n if (x + y) >= Solution::M {\n x + y - Solution::M\n } else {\n x + y\n }\n }\n\n fn mul(x: i64, y: i64) -> i64 {\n x * y % Solution::M\n }\n\n fn getz(s: &str) -> Vec<i64> {\n let n = s.len();\n let mut z = vec![0_i64; n];\n let mut left = 0;\n let mut right = 0;\n for i in 1..n {\n if i <= right && z[i - left] <= right as i64 - i as i64 {\n z[i] = z[i - left];\n } else {\n z[i] = std::cmp::max(0, right as i64 - i as i64 + 1);\n while i as i64 + z[i] < n as i64 && s.as_bytes()[i + z[i] as usize] == s.as_bytes()[z[i] as usize] {\n z[i] += 1;\n }\n }\n if i as i64 + z[i] - 1 > right as i64 {\n left = i;\n right = i + z[i] as usize - 1;\n }\n }\n z\n }\n\n fn mul2(a: &Vec<Vec<i64>>, b: &[Vec<i64>]) -> Vec<Vec<i64>> {\n let m = a.len();\n let n = a[0].len();\n let p = b[0].len();\n let mut r = vec![vec![0; p]; m];\n for i in 0..m {\n for (j, b_j) in b.iter().enumerate().take(n) {\n for (k, &b_j_k) in b_j.iter().enumerate().take(p) {\n r[i][k] = Solution::add(r[i][k], Solution::mul(a[i][j], b_j_k));\n }\n }\n }\n r\n }\n\n fn pow(a: &Vec<Vec<i64>>, y: i64) -> Vec<Vec<i64>> {\n let n = a.len();\n let mut r = vec![vec![0; n]; n];\n for (i, r_i) in r.iter_mut().enumerate().take(n) {\n r_i[i] = 1;\n }\n let mut x = a.clone();\n let mut y = y;\n while y > 0 {\n if y & 1 == 1 {\n r = Solution::mul2(&r, &x);\n }\n x = Solution::mul2(&x, &x);\n y >>= 1;\n }\n r\n }\n\n pub fn number_of_ways(s: String, t: String, k: i64) -> i32 {\n let n = s.len() as i64;\n let dp = &Solution::pow(&vec![vec![0_i64, 1], vec![n - 1, n - 2]], k)[0];\n let mut s = s;\n s.push_str(&t);\n s.push_str(&t);\n let z = Solution::getz(&s);\n let m = n + n;\n let mut r = 0;\n for i in n..m {\n if z[i as usize] >= n {\n r = Solution::add(r, dp[if (i - n) == 0 { 0 } else { 1 }]);\n }\n }\n r as _\n }\n}\n``` | 0 | 0 | ['Rust'] | 0 |
string-transformation | Python, solving a problem without being a genius. Matrix exponentiation + z-function | python-solving-a-problem-without-being-a-bjwu | Intuition\n\nThis is one of the problems that I almost solved during the competition and was very disappointed to not fully solve it.\n\n-------------------\n\n | salvadordali | NORMAL | 2023-10-05T07:24:44.336775+00:00 | 2023-10-05T07:24:44.336799+00:00 | 97 | false | # Intuition\n\nThis is one of the problems that I almost solved during the competition and was very disappointed to not fully solve it.\n\n-------------------\n\nFirst it is clear that the result is zero if a `s2` can\'t be created from `s1` with one operation. Which you can easily check with `if s2 in s1 + s1`\n\nI was not that smart to figure out recurrence relationship using math, I found it out emperically by writing a straighforward solution and trying to see the pattern. \n\nA straighforward soltuion:\n\n```python\ndef numberOfWays(self, s1: str, s2: str, k: int) -> int:\n data = {s1: 1}\n for j in range(k):\n tmp = defaultdict(int)\n for s, num in data.items():\n for i in range(1, len(s)):\n tmp[s[i:] + s[:i]] += num\n data = tmp\n return data[s2]\n```\n\nTrying it for different `k` on a couple of strings where `s1 != s2` and which do not have repetitions I found that the sequences depend on lenght of `s1`. So for:\n\n- `len(s) = 3`: https://oeis.org/A001045. `f(n) = f(n-1) + 2*f(n-2)`\n- `len(s) = 4`: https://oeis.org/A015518. `f(n) = 2*f(n-1) + 3*f(n-2)`\n- `len(s) = 5`: https://oeis.org/A015521. `f(n) = 3*f(n-1) + 4*f(n-2)`\n\nWhich gives you the following relationship: `f(n) = (l - 2) * f(n-1) + (l - 1) * f(n - 2)`. With starting conditions of `0, 1`\n\nThis would be easy if the `k` is small (million), but for bigger `k` we need to use matrix exponentiation. I will not be explaining it too much as there are [many](https://www.math.cmu.edu/~mradclif/teaching/228F16/recurrences.pdf) blog [posts](https://codeforces.com/blog/entry/67776) about it. In short you construct a matrix which represents the relationship: $v_n = A \\cdot v_{n - 1}$ and unrolling it you get v$_n = A^{n - 1} \\cdot v_0$\n\nNow you will need to implement matrix multiplication `_matmul` function and then ust it to do matrix exponentiation `_matrix_exp` (which is absolutely the same as normal exponentiation).\n\n\n--------------\n\nWe are two steps away from the full solution. Two steps are:\n\n - what if `s1 == s2`. The answer is easy. We either add `1` if `k` is even or subtract `1` if it is odd\n - what if `s1` and `s2` are strings which are created from repetitions.\n\n----\n\nSecond part I was not able to fully figure out. First what do I mean that they consist of repetitions? Given a string `s` if there exist another string `s\'` whose concatenation some amount of time create `s`\n\nYou can solve it by computing [z-function](https://cp-algorithms.com/string/z-function.html) and use it to find `num_repeats`.\n\nSo to get the final answer you need to do:\n - find result of recurrence using matrix exponentiation\n - multiply it by `num_repeats` which is taken as a min of repeats of two strings\n - if `s1 == s2` either add or remove one based on the parity of k\n\n\n\n\n\n# Complexity\n- Time complexity: $O(n)$\n- Space complexity: $O(n)$\n\n# Code\n```\nMOD = 10**9 + 7\n\nclass Solution:\n\n def _matmul(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:\n n = len(A)\n res = [[0] * n for _ in range(n)]\n for i in range(n):\n for j in range(n):\n res[i][j] = sum(A[i][k] * B[k][j] for k in range(n)) % MOD\n return res\n\n def _matrix_exp(self, M: List[List[int]], n: int) -> List[List[int]]:\n res = [[0] * i + [1] + [0] * (len(M) - i - 1) for i in range(len(M))]\n while n:\n if n % 2 == 1:\n res = self._matmul(res, M)\n M = self._matmul(M, M)\n n //= 2\n\n return res\n\n def z_function(self, s):\n z, l, r = [0] * len(s), 0, 0\n for i in range(1, len(s)):\n if i < r:\n z[i] = min(r - i, z[i - l])\n\n while i + z[i] < len(s) and s[z[i]] == s[i + z[i]]:\n z[i] += 1\n\n if i + z[i] > r:\n l = i\n r = i + z[i]\n\n return z\n\n def num_repeats(self, s):\n z = self.z_function(s)\n for i in range(len(s)):\n if i + z[i] >= len(s):\n return len(s) // i\n return 1\n\n def numberOfWays(self, s1: str, s2: str, k: int) -> int:\n if s2 not in s1 + s1:\n return 0\n\n num = min(self.num_repeats(s1), self.num_repeats(s2))\n M = [[len(s1) - 2, len(s2) - 1], [1, 0]]\n if k == 1:\n return M[1][0] * num - (s1 == s2)\n\n M_ = self._matrix_exp(M, k - 1)\n delta = -(s1 == s2) if k % 2 == 1 else (s1 == s2)\n\n return (M_[0][0] * num + delta) % MOD\n``` | 0 | 0 | ['Python3'] | 0 |
string-transformation | O(n+m+logk) kmp and fastmod | onmlogk-kmp-and-fastmod-by-lsfhv-b5wg | Use KMP (or any other algorithm) to find all occurances of t in s + s\n\nNotice that from taking any suffix and putting it at the front, is the same as just som | Lsfhv | NORMAL | 2023-09-14T19:12:06.341932+00:00 | 2023-09-14T19:12:06.341955+00:00 | 61 | false | Use KMP (or any other algorithm) to find all occurances of `t` in `s + s`\n\nNotice that from taking any suffix and putting it at the front, is the same as just some rotation in `s + s`. Let `i` be the index that corressponds to which rotation we are looking at. \nFor example in `abcd`, `s + s = abcdabcd` `i = 0` corresponds to `abcd`\n`i = 1` corresponds to `bcda` `i=2 => cdab` `i=3=>dabc`.\n\nIn one move, we can from any `i` to any other `i`\nLet `dp[k][i] = how many ways we can get the string starting at i` \nInitially we have dp[0][0] = 1 and every other value is 0\nFor example in `abcd`, `dp[0] = [1,0,0,0]`\nNext move we can have `dp[1] = [0,1,1,1]`\nNext we can have `dp[2] = [3,2,2,2]`\n\nNotice how all the values are the same except the first one? That is to be expected since we can move anywhere in any move!\n\nNow we only need to keep track of 2 states in each iteration, `dp[j][0]` and `dp[j][1]`, the statees of the jth iteration.\n\nNotice how can compute `dp[j][0] = dp[j-1][1] * (n-1)`\nand `dp[j][1] = (dp[j][1]*(n-2)) + dp[j][0]`\n\nSince k goes up to 1e15, we cant just go from 1 to k and compute the states.\n\nHeres the hard part of this question\nWe can represent the transition of states as the matrix \n`\n[\n [0,1], \n [n-1, n-2]\n]` (check this!)\nwhere `n` is the length of `s` \n\nComputing the next states reduces to just finding powers of that matrix which can be done quickly.\n\nFinally from the all the indicies that kmp returned, \nreturn `dp[k][0] * (how many matches at index 0) + dp[k][1] * (how many matches elsewhere)\n`\n\n\n# Code\n```\nclass Solution:\n def numberOfWays(self, s: str, t: str, k: int) -> int:\n mod = int(1e9 + 7)\n def m(A, B):\n return [[((A[0][0] * B[0][0]) + (A[0][1] * B[1][0])) % mod, ((A[0][0] * B[0][1]) + (A[0][1] * B[1][1])) % mod], [((A[1][0] * B[0][0]) + (A[1][1] * B[1][0]))%mod, ((A[1][0] * B[0][1]) + (A[1][1] * B[1][1])) % mod]]\n \n def fast(A, p):\n if p == 0:\n return [[1,0], [0,1]]\n x = fast(A, p // 2)\n x = m(x,x)\n\n if (p % 2 == 1):\n x = m(x,yyy)\n return x\n\n prefix = [0] * len(t)\n\n for i in range(1, len(t)):\n j = prefix[i - 1]\n while j>0 and t[j]!=t[i]:\n j = prefix[j - 1]\n \n if (t[j]==t[i]):\n j += 1\n prefix[i] = j\n s = s + s\n lst = []\n j = 0\n for i in range(0, len(s)):\n while j>0 and s[i] != t[j]:\n j = prefix[j - 1]\n if s[i] == t[j]:\n j += 1\n if j == len(t):\n if i + 1 - len(t) >= len(s)/2:\n break\n j = prefix[ j -1]\n lst.append(i + 1 - len(t))\n dp = [0] * (len(s)//2)\n dp[0] = 1\n n = len(s)//2\n yyy = [[0,1], [n-1, n-2]]\n first = 1\n rest = 0\n \n\n\n\n\n zzz = fast(yyy, k)\n\n\n\n first = zzz[0][0]\n rest = zzz[0][1]\n \n result =0 \n for i in lst:\n if i == 0:\n result += first\n else:\n result += rest \n result = result % mod\n return result\n \n``` | 0 | 1 | ['Python3'] | 0 |
string-transformation | Java easy solution --> String Transformation | java-easy-solution-string-transformation-yui9 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | ZIDDIRAJ | NORMAL | 2023-09-14T02:29:54.071354+00:00 | 2023-09-14T02:29:54.071374+00:00 | 568 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n private static final int Ma = 1000000007;\n\n private int add(int x, int y) {\n if ((x += y) >= Ma) {\n x -= Ma;\n }\n return x;\n }\n\n private int mul(long x, long y) {\n return (int) (x * y % Ma);\n }\n\n private int[] getZ(String s) {\n int n = s.length();\n int[] z = new int[n];\n for (int i = 1, left = 0, right = 0; i < n; ++i) {\n if (i <= right && z[i - left] <= right - i) {\n z[i] = z[i - left];\n } else {\n int z_i = Math.max(0, right - i + 1);\n while (i + z_i < n && s.charAt(i + z_i) == s.charAt(z_i)) {\n z_i++;\n }\n z[i] = z_i;\n }\n if (i + z[i] - 1 > right) {\n left = i;\n right = i + z[i] - 1;\n }\n }\n return z;\n }\n private int[][] matrixMultiply(int[][] a, int[][] b) {\n int m = a.length, n = a[0].length, p = b[0].length;\n int[][] r = new int[m][p];\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < p; ++j) {\n for (int k = 0; k < n; ++k) {\n r[i][j] = add(r[i][j], mul(a[i][k], b[k][j]));\n }\n }\n }\n return r;\n }\n private int[][] matrixPower(int[][] a, long y) {\n int n = a.length;\n int[][] r = new int[n][n];\n for (int i = 0; i < n; ++i) {\n r[i][i] = 1;\n }\n int[][] x = new int[n][n];\n for (int i = 0; i < n; ++i) {\n System.arraycopy(a[i], 0, x[i], 0, n);\n }\n while (y > 0) {\n if ((y & 1) == 1) {\n r = matrixMultiply(r, x);\n }\n x = matrixMultiply(x, x);\n y >>= 1;\n }\n return r;\n }\n\n public int numberOfWays(String s, String t, long k) {\n int n = s.length();\n int[] d = matrixPower(new int[][]{{0, 1}, {n - 1, n - 2}}, k)[0];\n s += t + t;\n int[] z = getZ(s);\n int m = n + n;\n int ans= 0;\n for (int i = n; i < m; ++i) {\n if (z[i] >= n) {\n ans = add(ans, d[i - n == 0 ? 0 : 1]);\n }\n }\n return ans;\n \n }\n}\n``` | 0 | 0 | ['Math', 'String', 'Dynamic Programming', 'Java'] | 0 |
string-transformation | [C++] Interesting linear recurrence with matrix exponentiation | c-interesting-linear-recurrence-with-mat-4iii | Intuition\nFirst notice that the operation reduces to rotations of at least 1 position. \n\nLet the target rotation be r, and we check how many such rotations t | nicholasfoocl | NORMAL | 2023-09-13T15:53:41.689871+00:00 | 2023-09-13T15:53:41.689901+00:00 | 89 | false | # Intuition\nFirst notice that the operation reduces to rotations of at least 1 position. \n\nLet the target rotation be `r`, and we check how many such rotations there are. Let the number of target rotations be `ct`.\n\nFrom there, we can work out a recurrence for dp:\n`v[i][0]` = number of ways to reach one of the ct target rotations after i steps\n`v[i][1]` = number of ways to reach one of the non-target rotations after i steps\nThe transitions are then:\nWe go to one of the `ct` positions from one of the `ct` positions in `ct-1` ways (we cannot do a full rotation)\nOR \nWe go to one of the `ct` positions from one of the non-target positions in `ct` ways\n`v[i][0] = v[i-1][0]*(ct-1) + v[i-1][1]*ct`\n\nVice versa for the other case:\n`v[i][1] = v[i-1][0]*(n-ct) + v[i-1][1]*(n-ct-1)`\nWe can factorize this into a matrix for our linear recurrence:\n```\nv[i][0] = (ct-1 ct ) v[i-1][0]\nv[i][1] = (n-ct n-ct-1) v[i-1][1]\n\nLet A = (ct-1 ct )\n (n-ct n-ct-1)\n```\nAnd do matrix exponentiation to find A^k\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFind the count of target positions with string hashing, then use matrix exponentiation to solve the linear recurrence\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nHashing: O(n) \nMatrix exponentiation: 2 * 2 * 2 * O(log K)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n) extra string `ns` in hashing\nO(log K) function call stack for matrix exponentiation\n\n# Code\n```\nclass Solution {\npublic:\n const long long MOD = 1e9+7;\n \n long long pow(long long x, long long n) {\n long long ans = 1;\n while(n){\n if(n&1){\n ans *= x;\n ans %= MOD;\n }\n x *= x;\n x %= MOD;\n n >>= 1;\n }\n return ans;\n }\n \n vector<vector<long long>> matMult(vector<vector<long long>>&a, vector<vector<long long>>&b){\n vector<vector<long long>> ans{{0,0},{0,0}};\n for(int i=0; i<2; i++){\n for(int j=0; j<2; j++){\n for(int k=0; k<2; k++){\n ans[i][j] += a[i][k]*b[k][j];\n ans[i][j] %= MOD;\n }\n }\n }\n return ans;\n }\n \n vector<vector<long long>> matPow(vector<vector<long long>>&v, long long n){\n vector<vector<long long>> ans{{1,0},{0,1}};\n while(n){\n if(n&1){\n ans = matMult(ans, v);\n }\n v = matMult(v,v);\n n >>= 1;\n }\n return ans;\n }\n \n long long getMatches(string&s, string&t){\n long long n = s.size();\n long long thash = 0;\n for(int i=0; i<n; i++){\n thash *= 31;\n thash += t[i]-\'a\';\n thash %= MOD;\n }\n long long ct = 0;\n long long hash = 0;\n long long power = pow(31,n-1);\n string ns = s+s;\n for(int i=0; i<n; i++){\n hash *= 31;\n hash %= MOD;\n hash += ns[i]-\'a\';\n hash %= MOD;\n }\n for(int i=n; i<2*n; i++){\n if(hash == thash) ct++;\n hash -= (ns[i-n]-\'a\')*power;\n hash %= MOD;\n hash += MOD;\n hash *= 31;\n hash %= MOD;\n hash += ns[i]-\'a\';\n hash %= MOD;\n }\n return ct;\n }\n\n int numberOfWays(string s, string t, long long k) {\n /*\n break it down into whether you\'re at ct or not at ct after however many steps\n v[i][0] = at ct,\n v[i][1] = not at ct;\n\n v[i][0] = v[i-1][0]*(ct-1) + v[i-1][1]*ct \n v[i][1] = v[i-1][0]*(n-ct) + v[i-1][1]*(n-ct-1) \n = (ct-1 ct ) v[i-1][0]\n = (n-ct n-ct-1) v[i-1][1]\n do matrix exp, want to find:\n A = ct-1 ct\n n-ct n-ct-1\n A^k\n */\n long long n = s.size();\n long long ct = getMatches(s,t);\n vector<vector<long long>> v{{ct-1, ct},{n-ct, n-ct-1}};\n auto ans = matPow(v, k);\n // return those that end in 0, and we select the base case based on whether s!=t\n return ans[0][s!=t];\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
string-transformation | KMP + Matrix exponentiation 90% faster | kmp-matrix-exponentiation-90-faster-by-v-rysu | Intuition\n Describe your first thoughts on how to solve this problem. \nthese transformations are nothing but rotations of S.\nsteps:\n1. check whether T is a | vedantnaudiyal | NORMAL | 2023-09-13T12:04:26.235075+00:00 | 2023-09-13T12:04:26.235098+00:00 | 93 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nthese transformations are nothing but rotations of S.\nsteps:\n1. check whether T is a possible rotation of S or not?\n2. if yes then no of possible rotations for a string str of length n will be n(including itself, rotating at i-> 0..n-1). Now since S and T are rrotations of one another so both have same set of rotation strings\n3. Now find out how many rotations of T are equal to itself.\n4. then apply matrix multiplication formula to get {op} ^ k using matrix exponentiation log(k).Then apply it on base vector {non-T strings present in initial state, T strings present in initial state} initial state is the given string.\n5. After applying the k operaations the no of T strings are the answer.\n\nNow, how to check 1. point, get the lps of S int T using KMP, then check the remaining strng if it is same then T is a rotation of S otherwise not.\nFor 3. point result will be equal to no of rotations of S equal to T since both have same set of rotations.\nGet the Lps of T in itself ie; the Pi table of KMP remaining length if rotated will form T itself.therefore, every rotation point of length multiple of k will also be T thus exactly n/k rotations of T/S are equal to T. There is a proof for this statement as well You can check it through some examples a swell.\nNow as for the operator is representing the formula 2 x 2maatrix after applying which we get the no. of non T and T strings in the next step.Mtrix exponentiation is used to get op ^ k.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n+log(k))\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n) + stack space\n\n**PLS UPVOTE IF IT HELPED**\n\n# Code\n```\nclass Solution {\npublic:\nint mod=1e9+7;\n int fun(string& s,int n){\n vector<int> pi(n);\n pi[0]=-1;\n int i=-1;\n int j=1;\n while(j<n){\n if(s[i+1]==s[j]){\n i++;\n pi[j]=i;\n j++;\n }\n else{\n if(i>=0){\n i=pi[i];\n }\n else{\n pi[j]=-1;\n j++;\n }\n }\n }\n return n-pi[n-1]-1;\n }\n int kmp(string& s,string& t){\n int n=s.size();\n vector<int> pi(n);\n pi[0]=-1;\n int i=-1;\n int j=1;\n while(j<n){\n if(s[i+1]==s[j]){\n i++;\n pi[j]=i;\n j++;\n }\n else{\n if(i>=0){\n i=pi[i];\n }\n else{\n pi[j]=-1;\n j++;\n }\n }\n }\n vector<int> lps(n);\n i=-1;j=0;\n while(j<n){\n if(s[i+1]==t[j]){\n i++;\n lps[j]=i;\n j++;\n }\n else{\n if(i>=0){\n i=pi[i];\n }\n else{\n lps[j]=-1;\n j++;\n }\n }\n }\n return lps[n-1]+1;\n }\n\n bool rot(string& s,string& t,int j){\n int i=0;\n int n=s.size();\n for(;j<n;j++){\n if(t[i]!=s[j]) return false;\n i++;\n }\n return true;\n }\n\n void mat_mul(int arr1[][2],int arr2[][2]){\n int a=((arr1[0][0]*1LL*arr2[0][0])%mod + (arr1[0][1]*1LL*arr2[1][0])%mod)%mod;\n int b=((arr1[0][0]*1LL*arr2[0][1])%mod+ (arr1[0][1]*1LL*arr2[1][1])%mod)%mod;\n int c=((arr1[1][0]*1LL*arr2[0][0])%mod+ (arr1[1][1]*1LL*arr2[1][0])%mod)%mod;\n int d=((arr1[1][0]*1LL*arr2[0][1])%mod+ (arr1[1][1]*1LL*arr2[1][1])%mod)%mod;\n arr1[0][0]=a;\n arr1[0][1]=b;\n arr1[1][0]=c;\n arr1[1][1]=d;\n }\n void fun(int arr[][2], int res[][2],long long k){\n if(k==0){\n res[0][0]=1;\n res[0][1]=0;\n res[1][0]=0;\n res[1][1]=1;\n return ;\n }\n long long x=k/2;\n fun(arr, res, x);\n mat_mul(res, res);\n if(k&1){\n mat_mul(res, arr);\n }\n }\n int numberOfWays(string s, string t, long long k) {\n int n=s.size();\n if(t.size()!=n) return 0;\n \n int x=kmp(s,t);\n if(x==0 || !rot(s,t,x)) return 0;\n int a=n/fun(s,n);\n int arr[2][2]={{n-1-a, n-a},{a, a-1}};\n int res[2][2];\n fun(arr, res, k);\n int vec[2]={};\n if(s==t) vec[1]=1;\n else vec[0]=1;\n \n return ((res[1][0]*1LL*vec[0]%mod) + (res[1][1]*1LL*vec[1]%mod))%mod;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
string-transformation | string hash and dp | string-hash-and-dp-by-sae_young-5cow | Complexity\n- Time complexity:\nO(max(N, log2K))\n\n- Space complexity:\nO(max(N, log2K))dynami\n\n# Code\n\nclass Solution {\n#define MOD 1000000007\n\npublic: | sae_young | NORMAL | 2023-09-12T23:30:38.068164+00:00 | 2023-09-12T23:30:38.068188+00:00 | 164 | false | # Complexity\n- Time complexity:\nO(max(N, log2K))\n\n- Space complexity:\nO(max(N, log2K))dynami\n\n# Code\n```\nclass Solution {\n#define MOD 1000000007\n\npublic:\n long long dp[55][2] = {{}};\n\n void init(long long k, int n) {\n dp[0][0] = 1;\n dp[0][1] = 0;\n\n int logK = (int)log2(k);\n\n for(int i=1; i<=logK; i++) {\n long long dd = (dp[i-1][0] * dp[i-1][0]) % MOD;\n long long ds = (dp[i-1][0] * dp[i-1][1]) % MOD;\n long long ss = (dp[i-1][1] * dp[i-1][1]) % MOD;\n dp[i][0] = ((n-2) * dd + 2 * ds) % MOD;\n dp[i][1] = ((n-1) * dd + ss) % MOD;\n }\n }\n\n vector<int> pos(string s, string t) {\n int n = s.size();\n\n long long p = 31, s_hash_sum = 0, t_hash_sum = 0;\n vector<long long> bs(n+1);\n bs[0] = 1;\n\n for(int i=n-1; i>=0; i--) {\n s_hash_sum = (s_hash_sum + (s[i] - \'a\') * bs[n-1-i]) % MOD;\n bs[n-i] = (bs[n-i-1] * p) % MOD;\n }\n\n vector<long long> t_hash(n, 0);\n\n for(int i=n-1; i>=0; i--) {\n t_hash[i] = ((t[i] - \'a\') * bs[n-1-i]) % MOD;\n t_hash_sum = (t_hash_sum + t_hash[i]) % MOD;\n }\n\n vector<int> ret;\n\n long long suffix_sum = 0;\n long long t_hash_sum_temp = t_hash_sum;\n\n for(int i=0; i<n; i++) {\n if(t_hash_sum == s_hash_sum) ret.push_back(i);\n\n t_hash_sum_temp = (t_hash_sum_temp - t_hash[i] + MOD) % MOD;\n suffix_sum = ((p * suffix_sum) + (t[i] - \'a\')) % MOD;\n\n t_hash_sum = ((t_hash_sum_temp) * bs[i+1] + suffix_sum) % MOD;\n }\n\n return ret;\n }\n\n long long solve(long long k, bool is_same, int n) {\n\n int logk = log2(k);\n\n long long ct[2] = {dp[logk][0],dp[logk][1]};\n\n k -= (1ll << logk);\n\n while(k > 0) {\n logk = log2(k);\n k -= (1ll << logk);\n \n long long dd = (ct[0] * dp[logk][0]) % MOD;\n long long ds = (ct[0] * dp[logk][1]) % MOD;\n long long sd = (ct[1] * dp[logk][0]) % MOD;\n long long ss = (ct[1] * dp[logk][1]) % MOD;\n ct[0] = ((n-2) * dd + ds + sd) % MOD;\n ct[1] = ((n-1) * dd + ss) % MOD;\n }\n\n return ct[is_same];\n }\n\n int numberOfWays(string s, string t, long long k) {\n int n = s.size();\n\n init(k, n);\n\n vector<int> ps = pos(s,t);\n\n long long ct[2] = {0,0};\n\n for(int p: ps) {\n ct[p == 0]++;\n }\n\n return ((ct[0] * solve(k, 0, n) % MOD) + (ct[1] * solve(k, 1, n) % MOD)) % MOD;\n }\n};\n``` | 0 | 0 | ['Dynamic Programming', 'String Matching', 'C++'] | 0 |
string-transformation | Binary Lifiting | binary-lifiting-by-xd91-i7nw | Intuition\nUsed binary lifting in several last contests\n\n# Approach\nBinary lifting\n\n# Complexity\n- Time complexity:\nhard to say it\'s O(n), the string co | xd91 | NORMAL | 2023-09-11T00:56:30.693493+00:00 | 2023-09-11T01:05:20.329917+00:00 | 40 | false | # Intuition\nUsed binary lifting in several last contests\n\n# Approach\nBinary lifting\n\n# Complexity\n- Time complexity:\nhard to say it\'s O(n), the string comparison is slow, and I failed to optimize it. String hashing gave me collisions. Hint shows that KMP should be used.\n\n- Space complexity: O(n)\n\n\n# Code\n```\nclass Solution:\n def numberOfWays(self, s: str, t: str, k: int) -> int:\n m = 10 ** 9 + 7\n n = len(s)\n\n\n equal_positions = 0\n\n if len(set(s)) == 1 and set(s) == set(t):\n equal_positions = n\n elif set(s) == set(t) == set(\'ab\'): # dirty hack\n equal_positions = n // 2\n else:\n for i in range(0, len(s)):\n if s[i] != t[0]:\n continue\n if s[i:] + s[:i] == t:\n equal_positions += 1\n\n unequal_positions = n - equal_positions\n\n # ways[is_equal][i], when string is equal to t, how many ways can make string become not equal or equal to t in 2 ** i operation\n ways = [[(0, 0)] * 50, [(0, 0)] * 50]\n for i in range(50):\n if i == 0:\n ways[0][i] = (unequal_positions - 1, equal_positions)\n ways[1][i] = (unequal_positions, equal_positions - 1)\n else:\n ways[0][i] = ((ways[0][i-1][1] * ways[1][i-1][0] + ways[0][i-1][0] * ways[0][i-1][0]) % m,\n (ways[0][i-1][1] * ways[1][i-1][1] + ways[0][i-1][0] * ways[0][i-1][1]) % m)\n\n ways[1][i] = ((ways[1][i-1][1] * ways[1][i-1][0] + ways[1][i-1][0] * ways[0][i-1][0]) % m,\n (ways[1][i-1][1] * ways[1][i-1][1] + ways[1][i-1][0] * ways[0][i-1][1]) % m)\n\n equals = 1 if s == t else 0\n unequals = 0 if s == t else 1\n for i in range(49, -1, -1):\n if 2 ** i <= k:\n k -= 2 ** i\n new_equals = (equals * ways[True][i][1] + unequals * ways[False][i][1]) % m\n new_unequals = (equals * ways[True][i][0] + unequals * ways[False][i][0]) % m\n equals, unequals = new_equals, new_unequals\n return equals % m\n\n\n\n\n\n``` | 0 | 0 | ['Python3'] | 0 |
string-transformation | Magic Solution | No DP No Tables | Pure Math | C++ | magic-solution-no-dp-no-tables-pure-math-8n4x | Intuition\nFirst of all let define that operations are actially do.\nImagine our string t as a looped string with some point, which we\'ll call the starting pos | KOCMOHABT | NORMAL | 2023-09-10T22:01:48.262357+00:00 | 2023-09-12T12:32:21.250776+00:00 | 105 | false | # Intuition\nFirst of all let define that operations are actially do.\nImagine our string $$t$$ as a looped string with some point, which we\'ll call the starting position. Any operation just rolls over our string and changes this position. Operation with a suffix length of $$l$$ clearly shifts our position by $$l$$.\n\nOur goal is to make the starting positions of the strings $$s$$ and $$t$$ identical after $$k$$ operations. If these strings are different in the term of a looped string, then there is no way to do it, and we will return 0.\nIf the string are the same in the term of a looped string, then we can make them identical any time just by shifting the starting position of $$s$$ by difference between starting position of $$s$$ and $$t$$. Also there is can be more than one position that makes looped string be identical to $$t$$.\n\nWe should count the number of such positions. \nI won\'t stop on the counting process, I\'ll just say that in my approach the Z algorithm was used to search for all occurrences of a substring.\n\nLet\'s next $$n$$ - is the length of the string $$s$$.\n$$m$$ - the number of such identical positions.\n\nExample:\n```\ns="codecode"\nt="odecodec"\n\nn=8\nm=2\n\nThe identical positions in s is 1 and 4\n\ns="ababab"\nt="ababab"\n\nn=6\nm=3\n\nThe identical positions in s is 0, 2 and 4\n```\n\nIf $$m = 0$$ then $$s$$ and $$t$$ are different in terms of a looped string and we can\'t make them identical, so in that case we return $$0$$.\n\nWe will start from $$k=1$$\n\nThere are only 2 cases:\n1. $$s = t$$ from start, or in our terms the starting position of $$s$$ is one of the identical to $$t$$\nSo, since we have just 1 operation and since we can\'t shift by $$0$$ there is only $$m - 1$$ positions where we can shift our $$s$$\n2. Otherwise, since the starting position of $$s$$ is not one of the identical to $$t$$ then we can shift to any identical position.\n\nLet\'s name \n$$I(k)$$ - count of possible ways to make $$t$$ and $$s$$ equal in $$k$$ operations if starting position of $$s$$ is on of the identical\n\n$$N(k)$$ - same but for non-identical position\n\nAs was mentioned above, we can conclude that\n$$I(1)=m-1$$ and $$N(1)=m$$\n\nNext, let\'s say we know $$I(k-1)$$ and $$N(k-1)$$\n\nIf we stay at identical positon then we can shift to any of $$m - 1$$ identical positions or to any of $$n - m$$ non identical positions. So $$I(k)=(m-1)*I(k-1) + (n - m)*N(k-1)$$\nSimilarly, if we stay at non-identical position we can shit to any of $$m$$ identical positions or to any of $$n - m - 1$$ non-identical positons, therefore $$N(k) = m * I(k-1) + (n -m - 1)*N(k-1)$$\n\nIn fact, this is it. Now to count the result we need to determine are we at identical position at the start or not and use one of equations above. But since $$k$$ is very large we will get TLE if we will try to use it this way.\n\nWe need to learn how to calculate these equations in a non-recursive way. Let\' rewrite our equations\n\n$$I(k)=(m-1)*I(k-1) + (n - m)*N(k-1) = m*I(k-1) + (n - m)*N(k-1) - I(k-1)$$\n$$N(k) = m * I(k-1) + (n -m - 1)*N(k-1)=m * I(k-1) + (n -m)*N(k-1) - N(k-1)$$\n\nBoth have a common part, let\'s name it \n$$C(k)= m*I(k) + (n - m)*N(k)$$\nso\n$$I(k)=C(k - 1) - I(k-1)$$\n$$N(k) = C(k - 1) - N(k-1)$$\nLooks better and simpler now. Let\'s try to express $$C(k)$$ through $$C(k-1)$$\n$$C(k)= m*I(k) + (n - m)*N(k) = m * (C(k - 1) - I(k - 1)) + (n - m)* (C(k - 1) - N(k - 1)) = n*C(k - 1) - m*I(k -1) - (n-m)*N(k - 1)=n*C(k - 1) - (m*I(k -1) + (n-m)*N(k - 1))=n*C(k - 1) - C(k - 1)= (n - 1) * C(k - 1)$$\nAt the end:\n$$C(k)= (n - 1) * C(k - 1)$$ therefore $$C(k)= (n - 1)^{k-1} * C(1)$$\n\nCool, now we can calculate $$C(k)$$ without recursion. But what about $$I(k)$$ and $$N(k)$$?\n\n$$I(k)=C(k - 1) - I(k-1)= C(k - 1) - C(k - 2) + C(k - 3) + ... + (-1)^{k-2} * C(1) + (-1)^{k - 1}*I(1)=(n - 1)^{k-2} * C(1) - (n - 1)^{k-3} * C(1) + (n - 1)^{k-4} * C(1) + ... + (-1)^{k-2} * (n - 1)^{0} * C(1) + (-1)^{k - 1}*I(1) = C(1) * ((n - 1)^{k-2} - (n - 1)^{k-3} + (n - 1)^{k-4} + ... + (-1)^{k-2} * (n - 1)^{0}) + (-1)^{k - 1}*I(1)$$\n\nLet\'t call $$SumOfPowers(n, k) = n^{k-1} - n^{k-2} + n^{k-3} + ... + (-1)^{k-1} * n^{0}$$ then\n$$I(k) = SumOfPowers(n - 1, k - 1) * C(1) + (-1)^{k - 1}*I(1)$$\nBy the same calculations we get\n$$N(k) = SumOfPowers(n - 1, k - 1) * C(1) + (-1)^{k - 1}*N(1)$$\n\nSo now we need to learn how to calculate our $$SumOfPowers$$ without any recursion.\nWe will use the same exponential method that is used to calculate ordinary powers of a number.\n\nIf $$k$$ is odd then\n\n$$SumOfPowers(n, k) = n^{k-1} - n^{k-2} + n^{k-3} + ... + 1 = n*(n^{k-2} - n^{k-3} + ... -1) + 1 = n * SumOfPowers(n, k - 1) + 1$$\nIf $$k$$ is even then \n$$SumOfPowers(n, k) = n^{k-1} - n^{k-2} + ... + (-1)^{k/2 - 1} n^{k/2 } + (-1)^{k/2} n^{k/2 - 1} + ... + (-1)^{k-1}=n^{k/2} * (n^{k/2-1}- n^{k/2 - 2}+... + (-1)^{k / 2-1}) + (-1)^{k/2} * (n^{k/2-1}- n^{k/2 - 2}+... + (-1)^{k / 2-1})=n^{k/2}*SumOfPowers(n, k / 2) + (-1)^{k/2} * SumOfPowers(n, k / 2)$$.\n\n$$C(1) = m*I(1) + (n - m)*N(1)=m*(m-1)+(n-m)*m=n*m-m$$\nSo the result will be:\nIf we stand at identical position in the beginning\n$$(m*n-m) * SumOfPowers(n - 1, k - 1) + (-1)^{k-1} * (m-1)$$\nelse\n$$(m*n-m) * SumOfPowers(n - 1, k - 1) + (-1)^{k-1} * m$$\n\n\n# Code\n```\n#define MOD 1000000007\nclass Solution \n{\npublic:\n\n int numberOfWays(std::string& s, std::string& t, long long k)\n {\n long long n = s.size();\n long long m = 0;\n\n int len = s.size();\n t.append("@");\n t.append(s);\n t.append(s);\n int Z[t.size()];\n initZ(t, Z); \n\n for (int i = len + 1; i < 2 * len + 1; ++i)\n {\n if (Z[i] == len)\n ++m;\n }\n\n bool fromStart = Z[len + 1] == len;\n\n if (!m)\n return 0;\n\n return (((m * n - m) % MOD) * getSumOfPowers(n - 1, k - 1) % MOD + (k & 1 ? 1 : -1) * (fromStart ? m - 1 : m)) % MOD;\n }\n \nprivate:\n \n long long getPower(long long x, long long k)\n {\n if (k <= 0)\n return 1;\n\n if (k & 1)\n {\n return x * getPower(x, k - 1) % MOD;\n }\n else\n {\n long long r = getPower(x, k >> 1) % MOD;\n return (r * r) % MOD;\n }\n }\n\n long long getSumOfPowers(long long x, long long k)\n {\n if (k <= 0)\n return 0;\n\n if (k & 1)\n {\n return (x * getSumOfPowers(x, k - 1) + 1) % MOD;\n }\n else\n {\n long long k_2 = k >> 1;\n long long r = getSumOfPowers(x, k_2) % MOD;\n return (getPower(x, k_2) * r + (k_2 & 1 ? - r : r)) % MOD;\n }\n }\n\n void initZ(std::string& s, int Z[])\n {\n int l = 0;\n int r = 0;\n for (int i = 1, n = s.size(); i < n; ++i)\n {\n if (i > r)\n {\n l = i;\n r = i;\n \n while (r < n && s[r - l] == s[r])\n ++r;\n\n Z[i] = r - l;\n --r;\n }\n else\n {\n int k = i - l;\n \n if (Z[k] < r - i + 1)\n {\n Z[i] = Z[k]; \n }\n else\n {\n l = i;\n while (r < n && s[r - l] == s[r])\n ++r;\n Z[i] = r - l;\n --r;\n }\n }\n }\n }\n\n};\n``` | 0 | 0 | ['C++'] | 0 |
string-transformation | C++ Rabin-Karp + DP-Matrix Exponentiation. | c-rabin-karp-dp-matrix-exponentiation-by-gzis | Initial intuition is that our operation is a rotation operation only. Just rotation, not swap or anything suspicious like that. There are only upto N unique rot | satj | NORMAL | 2023-09-10T21:27:48.231011+00:00 | 2023-09-12T16:28:27.777842+00:00 | 54 | false | Initial intuition is that our operation is a rotation operation only. Just rotation, not swap or anything suspicious like that. There are only upto `N` unique rotations.\n\nUse $$previous\\ knowledge \u2122$$ to do Rabin-Karp/KMP/Z to find how many ways we can get from out initial string `s` to target string `t` by rotating our string `s` and checking against `t`. Let\'s call this number `M`. Say length of our string is `N`.\n\nLet `s` be some current rotation of original string and `s\'` be some rotation we are considering going into. With `N` being long it may look like many options, but there are really only 4 options to consider.\n\n* We can rotate to any `s\' != t` with `N - M - 1` ways (from any `s != t` position, can\'t rotate into self)\n* We can rotate to any `s\' != t` with `N - M` ways (from any `s == t` position)\n* We can rotate to any `s\' == t` with `M` ways (from any `s != t` position)\n* We can rotate to any `s\' == t` with `M - 1` ways (from any `s == t` position, can\'t rotate into self)\n\nWith that equipped and having $$previous\\ knowledge$$ of DP + Matrix Exponentiation we can construct our transition matrix and get the result. \n```\ntypedef vector <vector <long long>> vvl;\nclass Solution {\npublic:\n long mod = 1e9 + 7;\n long p = 31;\n int getRots(string &s, string &t) {\n int ret = 0;\n long hasht = 0;\n long hashs = 0;\n int n = s.size();\n long pp = 1;\n for (int i = n - 1; i >= 0; i--) {\n hasht = (hasht * p + t[i] - \'a\' + 1) % mod;\n hashs = (hashs * p + s[i] - \'a\' + 1) % mod;\n if (i > 0)\n pp = (pp * p) % mod;\n }\n if (hasht == hashs) ret++;\n for (int i = n - 1; i > 0; i--) {\n int c = s[i] - \'a\' + 1;\n hashs = ((hashs - c * pp + mod * p) * p + c) % mod;\n if (hashs == hasht)\n ret++;\n }\n return ret;\n }\n vvl matMult(vvl a, vvl b) {\n vvl ret = { {0, 0}, {0, 0} };\n for (int i = 0; i < 2; i++)\n for (int j = 0; j < 2; j++)\n for (int k = 0; k < 2; k++)\n ret[i][j] = (ret[i][j] + a[i][k] * b[k][j]) % mod;\n return ret;\n }\n vvl matrixExp(vvl mat, long k) {\n vvl ret = { {1, 0}, {0, 1} };\n while (k > 0) {\n if (k % 2 == 1)\n ret = matMult(ret, mat);\n mat = matMult(mat, mat);\n k /= 2;\n }\n return ret;\n }\n int numberOfWays(string s, string t, long long k) {\n auto rots = getRots(s, t);\n if (rots == 0) \n return 0;\n int v1 = s.size() - rots, v2 = rots;\n vvl mat = {\n {v1 - 1, v1},\n {v2, v2 - 1}\n };\n auto ret = matrixExp(mat, k);\n return ret[1][s == t];\n }\n};\n``` | 0 | 0 | ['C'] | 0 |
string-transformation | [c++] rolling hash | c-rolling-hash-by-lyronly-0yc2 | 1 Use similar concept as Binary lifting for caculatting the transform matrix for k.\n2 use rolling hash to detech pattern in string s\'s rotations.\n\n\nclass S | lyronly | NORMAL | 2023-09-10T19:15:00.710478+00:00 | 2023-09-10T19:15:00.710501+00:00 | 25 | false | 1 Use similar concept as Binary lifting for caculatting the transform matrix for k.\n2 use rolling hash to detech pattern in string s\'s rotations.\n\n```\nclass Solution {\npublic:\n const int mod = (int)(1e9 +7);\n int add(int x, int y) {\n if ((x += y) >= mod) {\n x -= mod;\n }\n return x;\n }\n\n int mul(long long x, long long y) {\n return x * y % mod;\n }\n \n vector<vector<int>> mul(const vector<vector<int>> &a, const vector<vector<int>> &b) {\n const int m = a.size(), n = a[0].size(), p = b[0].size();\n vector<vector<int>> r(m, vector<int>(p));\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n for (int k = 0; k < p; ++k) {\n r[i][k] = add(r[i][k], mul(a[i][j], b[j][k]));\n }\n }\n }\n return r;\n }\n \n long long M = mod;\n vector<vector<int>> pow(vector<vector<int>>& a, long long k) {\n int n = a.size();\n long long bit = 1;\n int i = 0;\n vector<vector<int>> ans(n, vector<int>(n, 0));\n for (int i = 0; i < n; i++) ans[i][i] = 1;\n vector<vector<int>> cur = a;\n while (bit <= k) {\n \n if ((bit & k) != 0) {\n ans = mul(ans, cur);\n }\n cur = mul(cur, cur);\n bit = bit << 1;\n }\n return ans;\n }\n \n int numberOfWays(string s, string t, long long k) {\n string s2 = s + s;\n int n = s.size();\n \n long long pre = 1;\n long long ht = 0;\n for (int i = 0; i < n; i++) {\n pre = (pre * 26L) % M;\n ht = (ht * 26L) % M;\n ht = (ht + t[i] - \'a\') % M;\n }\n \n long long hash = 0;\n vector<int> dp(n, 0);\n for (int i = 0; i < n + n - 1; i++) {\n hash = (hash * 26L) % M;\n hash = (hash + s2[i] - \'a\') % M;\n \n if (i >= n) {\n hash = (hash + M - (pre * (s2[i - n] - \'a\'))%M) % M;\n }\n if (i >= n -1) {\n int j = i - (n - 1);\n if (hash == ht) {\n dp[j] = 1;\n }\n }\n }\n \n vector<vector<int>> mat = {{0, 1}, {n -1, n - 2}};\n vector<vector<int>> a = {{1, 0}};\n vector<vector<int>> kk = pow(mat, k);\n vector<vector<int>> b = mul(a, kk);\n int x = b[0][0];\n int y = b[0][1];\n int ans = 0;\n for (int i = 0; i < n; i++) {\n int v = 0;\n if (dp[i] == 1) {\n if (i == 0) v = x;\n else v = y; \n }\n ans = add(ans , v);\n }\n \n return ans;\n }\n};\n``` | 0 | 0 | [] | 0 |
string-transformation | JS Solution | js-solution-by-cutetn-mth3 | LOL contests these days are painfully hard.\n\n# Approach\n- To save your time, the full solution involves hash, inversed modulo, generating function.\n\n- let | CuteTN | NORMAL | 2023-09-10T16:40:24.255040+00:00 | 2023-09-10T16:40:24.255062+00:00 | 188 | false | LOL contests these days are painfully hard.\n\n# Approach\n- To save your time, the full solution involves **hash**, **inversed modulo**, **generating function**.\n\n- let `l = t.length`\n- A simple trick to find a rotation of `s` that equals to `t` is to find all occurrence of `t` in `s + s` (which starts before index `l` of `s + s`).\n- If you\'re like me, lazy enough to implement any fancy algorithms on finding occurrence in a string, you should use **Hash**. With the technique, we can calculate:\n- $$z$$ is the number of valid rotation at index 0 (technically, it\'s just `z = s === t? 1 : 0`).\n- $$c$$ is the total number of valid rotations.\n\n- Let `dp[k]` be the answer to the problem, we have:\n```js\ndp[0] = z\ndp[1] = c - z\ndp[i] = (l-2) * dp[i-1] + (l-1) * dp[i-2]\n```\n\n- Since `k` is ridiculously large, we need to optimize this formula, 2 techniques can be taken into consideration is **matrix multiplication** or **generating function**. I opted for the latter. So the general formula would be:\n$$dp[i] = ((l - 1)^k * c + (-1)^k * (z * l - c)) / l$$\n- I have a marvelous proof for this but this text area is too narrow. :^( \n\n# Complexity\n- Time complexity: $$O(s.length + t.length + log(k))$$\n- Space complexity: $$O(s.length)$$\n\n# Code\n```js\nclass Modulo {\n /**\n * @param {number} modulo\n */\n constructor(modulo) {\n /** @type {number} @readonly */\n this.modulo = modulo;\n\n /** @private @type {undefined | number} */\n this._phi = undefined;\n }\n\n /**\n * @returns {number}\n */\n getPhi() {\n if (this._phi !== undefined) return this._phi;\n\n let result = this.modulo;\n let temp = this.modulo;\n for (let i = 2; i <= Math.sqrt(temp); i++) {\n if (temp % i === 0) {\n result /= i;\n result *= i - 1;\n }\n while (temp % i === 0) temp /= i;\n }\n if (temp > 1) {\n result /= temp;\n result *= temp - 1;\n }\n\n this._phi = result;\n return result;\n }\n\n /**\n * @param {number} a\n * @returns {number}\n */\n getInverse(a) {\n return this.pow(a, this.getPhi() - 1);\n }\n\n /**\n * @param {...number} numbers\n */\n add(...numbers) {\n let result = 0;\n for (let number of numbers) {\n result = (result + (number % this.modulo)) % this.modulo;\n }\n\n if (result < 0) result += this.modulo;\n return result;\n }\n\n /**\n * @private\n * @param {number} a\n * @param {number} b\n * @returns {number}\n */\n _quickMul(a, b) {\n a = ((a % this.modulo) + this.modulo) % this.modulo;\n b = ((b % this.modulo) + this.modulo) % this.modulo;\n if (a === 0 || b === 0) return 0;\n\n let result = 0;\n while (b) {\n while (b % 2 === 0) {\n a = (a * 2) % this.modulo;\n b /= 2;\n }\n\n if (b % 2 !== 0) {\n result = (result + a) % this.modulo;\n b--;\n }\n }\n\n return result;\n }\n\n /**\n * @param {...number} numbers\n */\n mul(...numbers) {\n let result = 1;\n for (let number of numbers) {\n if (number > 0 && number < 1)\n number = this.getInverse(Math.round(1 / number));\n result = this._quickMul(result, number);\n if (result === 0) return 0;\n }\n\n if (result < 0) result += this.modulo;\n return result;\n }\n\n /**\n * @param {number} a\n * @param {number} b\n * @returns {number}\n */\n div(a, b) {\n return this._quickMul(a, this.getInverse(b));\n }\n\n /**\n * @param {number} a\n * @param {number} b\n * @returns {number}\n */\n pow(a, b) {\n a = ((a % this.modulo) + this.modulo) % this.modulo;\n if (a === 0) return 0;\n\n let result = 1;\n while (b) {\n while (b % 2 === 0) {\n a = this._quickMul(a, a);\n b /= 2;\n }\n\n if (b % 2 !== 0) {\n result = this._quickMul(result, a);\n b--;\n }\n }\n\n return result;\n }\n}\n\nconst mod = new Modulo(1000000007);\n\n/**\n * @param {string} s\n * @param {string} t\n * @param {number} k\n * @return {number}\n */\nvar numberOfWays = function (s, t, k) {\n s += s;\n // const MOD = 1000000007;\n const BASE = 26;\n\n const basePows = [1];\n function getBasePow(n) {\n while (n >= basePows.length) {\n basePows.push(mod.mul(basePows[basePows.length - 1], BASE));\n }\n return basePows[n];\n }\n\n /** @param {string} s */\n function calcHashWord(s, pre = 0) {\n let result = pre;\n for (let i = 0; i < s.length; i++) {\n result = mod.add(\n mod.mul(result, BASE),\n mod.mul(1 + s.charCodeAt(i), s.charCodeAt(i))\n );\n }\n return result;\n }\n\n const prefixHash = [];\n prefixHash[-1] = 0;\n\n for (let i = 0; i < s.length; i++) {\n prefixHash.push(calcHashWord(s[i], prefixHash[prefixHash.length - 1]));\n }\n\n function getHash(l, r) {\n return mod.add(\n prefixHash[r],\n -mod.mul(prefixHash[l - 1], getBasePow(r - l + 1))\n );\n }\n\n const hashedT = calcHashWord(t, 0);\n let cntOcc = 0;\n let flagFirstMatch = 0;\n if (getHash(0, t.length - 1) === hashedT) {\n cntOcc++;\n flagFirstMatch = 1;\n }\n\n for (let i = 1; i < t.length; i++) {\n if (getHash(i, i + t.length - 1) === hashedT) cntOcc++;\n }\n\n if (k == 1) return cntOcc - flagFirstMatch;\n let res = mod.mul(cntOcc, mod.pow(t.length - 1, k));\n res = mod.add(\n res,\n mod.mul(flagFirstMatch * t.length - cntOcc, k % 2 ? -1 : 1)\n );\n res = mod.div(res, t.length);\n\n return res;\n};\n``` | 0 | 0 | ['Math', 'Dynamic Programming', 'JavaScript'] | 0 |
string-transformation | My Solution | my-solution-by-hope_ma-i2zd | \n/**\n * the dp solution is employed\n *\n * 1. dp1[i] stands for the number of the ways\n * in which `s` can be transformed into `t` in exactly `i` operati | hope_ma | NORMAL | 2023-09-10T10:47:51.806937+00:00 | 2023-12-10T11:34:17.333849+00:00 | 15 | false | ```\n/**\n * the dp solution is employed\n *\n * 1. dp1[i] stands for the number of the ways\n * in which `s` can be transformed into `t` in exactly `i` operations\n * 2. dp2[i] stands for the number of the ways\n * in which `s` can be tranfromed into a string which is not equal to `t`\n * in exactly `i` operations\n * where `i` is in the range [0, k], both inclusive\n *\n * let `n` be the length of the string `s`\n * let `matched` be the number of the different indices `i`\n * such that the string `s.substr(s.begin() + i) + s.substr(s.begin(), i)`\n * is equal to `t`, where `i` is in the range [0, `n` - 1], both inclusive\n *\n * initial:\n * dp1[0] = s == t ? 1 : 0\n * dp2[0] = s == t ? 0 : 1\n *\n * induction:\n * dp1[i] = (matched - 1) * dp1[i - 1] + matched * dp2[i - 1]\n * dp2[i] = (n - matched) * dp1[i - 1] + (n - matched - 1) * dp2[i - 1]\n * which is equivalent to,\n * __ __ __ __ __ __\n * | dp1[i] | | matched - 1, matched | | dp1[i - 1] |\n * | | = | | * | |\n * | dp2[i] | | n - matched, n - matched - 1 | | dp2[i - 1] |\n * -- -- -- -- -- --\n *\n * target:\n * __ __ __ __k __ __\n * | dp1[k] | | matched - 1, matched | | dp1[0] |\n * | | = | | * | |\n * | dp2[k] | | n - matched, n - matched - 1 | | dp2[0] |\n * -- -- -- -- -- --\n *\n * Time Complexity: O(n + log(k))\n * Space Complexity: O(n)\n * where `n` is the length of the string `s`\n */\nclass Solution {\n private:\n static constexpr int mod = 1000000007;\n \n class Matrix {\n private:\n static constexpr int n = 2;\n using row_t = array<int, n>;\n using matrix_t = array<row_t, n>;\n \n public:\n Matrix() : data_{row_t{0, 0}, row_t{0, 0}} {\n }\n \n Matrix(const row_t &row1, const row_t &row2) : data_{row1, row2} {\n }\n \n Matrix operator*(const Matrix &rhs) const noexcept {\n Matrix ret;\n for (int r = 0; r < n; ++r) {\n for (int c = 0; c < n; ++c) {\n for (int k = 0; k < n; ++k) {\n ret.data_[r][c] = (\n ret.data_[r][c] +\n static_cast<int>(static_cast<long long>(data_[r][k]) * rhs.data_[k][c] % mod)\n ) % mod;\n }\n }\n }\n return ret;\n }\n \n int result(const int dp1, const int dp2) const {\n return (static_cast<int>(static_cast<long long>(data_[0][0]) * dp1 % mod) +\n static_cast<int>(static_cast<long long>(data_[0][1]) * dp2 % mod)) % mod;\n }\n \n Matrix power(const long long k) const {\n Matrix ret{{1, 0}, {0, 1}};\n Matrix factor = *this;\n for (long long p = k; p > 0; p >>= 1) {\n if ((p & 0b1) == 0b1) {\n ret = ret * factor;\n }\n factor = factor * factor;\n }\n return ret;\n }\n \n private:\n matrix_t data_;\n };\n\n public:\n int numberOfWays(const string &s, const string &t, const long long k) {\n const int n = static_cast<int>(s.size());\n const int matched = get_matched(s, t);\n const Matrix matrix({matched - 1, matched}, {n - matched, n - matched - 1});\n const bool s_equal_t = s == t;\n return matrix.power(k).result(s_equal_t ? 1 : 0, s_equal_t ? 0 : 1);\n }\n \n private:\n int get_matched(const string &s, const string &t) {\n constexpr char separator = \'#\';\n const int n = static_cast<int>(s.size());\n string pattern;\n pattern.append(t).append(1, separator).append(s).append(s);\n pattern.pop_back();\n const int n_pattern = static_cast<int>(pattern.size());\n int next[n_pattern + 1];\n memset(next, 0, sizeof(next));\n next[0] = -1;\n for (int i = 0, j = -1; i < n_pattern; ) {\n if (j == -1 || pattern[i] == pattern[j]) {\n ++i;\n ++j;\n next[i] = j;\n } else {\n j = next[j];\n }\n }\n \n return count(next + 2 * n + 1, next + n_pattern + 1, n);\n }\n};\n``` | 0 | 0 | [] | 0 |
string-transformation | kmp, binary lifting and matrix multiply | kmp-binary-lifting-and-matrix-multiply-b-34bo | \n 1) use KMP to find all rotation index locations\n\n 2) Suppose that the initial state for number of ways is [x, y].\n x is the ways for zero, and y | wuzhenhai | NORMAL | 2023-09-10T08:45:21.326183+00:00 | 2023-09-10T08:46:58.849034+00:00 | 91 | false | \n 1) use KMP to find all rotation index locations\n\n 2) Suppose that the initial state for number of ways is [x, y].\n x is the ways for zero, and y is the ways for none-zeros.\n The next state after one operation can use the following formula:\n [new_x, new_y] = [x,y] * M, M = [[0,1], [n-1, n-2]].\n M is the transformation matrix.\n n is the length of s.\n\n 3) pseudocode(try to mod 1000000007 if you need):\n [x,y] = [1,0]\n M = [[0,1], [n-1, n-2]]\n while k != 0:\n if k%2 == 1:\n [x,y] = [x,y] * M\n # binary lifting to decrease the time complexity.\n k >>= 1\n M = M * M\n\n s = s + s\n remove the last char in the s.\n\n result = 0\n for i in kmp(s, t):\n if i == 0:\n result += x\n else:\n result += y\n\n\n\n```\nclass StringAlgorithm {\npublic:\n\tstatic std::vector<int> getNext(const std::string& s) {\n\t\tint n = s.size();\n\t\tstd::vector<int> pi(n, 0);\n\t\tfor (int i = 1; i < n; ++i) {\n\t\t\tint j = pi[i - 1];\n\t\t\twhile (j > 0 && s[j] != s[i]) j = pi[j - 1];\n\t\t\tif (j == 0 && s[0] != s[i]) pi[i] = 0;\n\t\t\telse pi[i] = j + 1;\n\t\t}\n\t\treturn pi;\n\t}\n\tstatic vector<int> kmp(const std::string& s, const std::string& t) {\n\t\tstd::vector<int> pi = getNext(t);\n\t\tint m = s.size(), n = t.size();\n\t\tint j = 0;\n\t\tvector<int> res;\n\t\tfor (int i = 0; i < m; ++i) {\n\t\t\twhile (j > 0 && s[i] != t[j]) j = pi[j - 1];\n\t\t\tif (s[i] == t[j]) j++;\n\t\t\tif (j == n) res.push_back(i - n + 1);\n\t\t}\n\t\treturn res;\n\t}\n};\n\nclass Solution {\npublic:\n\tint numberOfWays(string s, string t, long long k) {\n\t\tconst int n = s.size();\n\t\tfor (int i = 0; i + 1 < n; i++)\n\t\t{\n\t\t\ts.push_back(s[i]);\n\t\t}\n\n\t\tauto locations = StringAlgorithm::kmp(s, t);\n\n\n\t\t//x,n-1\u4E2Ay.\n\t\t// [[x, y]] * [[0,1],[n-1, n-2]]\n\n\t\tint64_t x = 1;\n\t\tint64_t y = 0;\n\n\t\tint arr[2][2] = { {0,1},{n - 1,n - 2} };\n\n\n\n\n\n\t\twhile (k)\n\t\t{\n\t\t\tint64_t a00 = arr[0][0];\n\t\t\tint64_t a01 = arr[0][1];\n\t\t\tint64_t a10 = arr[1][0];\n\t\t\tint64_t a11 = arr[1][1];\n\t\t\tif (k % 2)\n\t\t\t{\n\t\t\t\tauto oldx = x;\n\t\t\t\tauto oldy = y;\n\n\t\t\t\tx = oldx * a00 + oldy * a10;\n\t\t\t\ty = oldx * a01 + oldy * a11;\n\n\t\t\t\tx %= 1000000007;\n\t\t\t\ty %= 1000000007;\n\t\t\t}\n\t\t\tk >>= 1;\n\n\n\t\t\tarr[0][0] = (a00 * a00 + a01 * a10) % 1000000007;\n\t\t\tarr[0][1] = (a00 * a01 + a01 * a11) % 1000000007;\n\t\t\tarr[1][0] = (a10 * a00 + a11 * a10) % 1000000007;\n\t\t\tarr[1][1] = (a10 * a01 + a11 * a11) % 1000000007;\n\t\t}\n\n\t\tint64_t res{};\n\t\tfor (auto l : locations)\n\t\t{\n\t\t\tif (l) res += y;\n\t\t\telse res += x;\n\t\t\tres %= 1000000007;\n\t\t}\n\t\treturn res;\n\t}\n};\n```\n | 0 | 0 | ['C++'] | 0 |
string-transformation | Transition Matrix Solution | transition-matrix-solution-by-hongyili-2qy0 | Intuition\n Describe your first thoughts on how to solve this problem. \nFrist find number of rotation-shift\'s to make\n\nSecond, create transition matrix of r | hongyili | NORMAL | 2023-09-10T04:26:04.014473+00:00 | 2023-09-10T04:26:04.014491+00:00 | 190 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFrist find number of rotation-shift\'s to make\n\nSecond, create transition matrix of rotation-shift. This matrix is tricky, it has 0 in diagonal and 1 elsewhere. If we calculate powers of this matrix, we will see there are only 2 values, diagonal and off-diagonal. So we can solve for this 2 values given number of transitions.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCalculate transition by DP.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n + log(k))\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n * log(k))\n\n# Code\n```\nclass Solution:\n def helper(self, i):\n if i in self.mem:\n return self.mem[i]\n \n r1 = self.helper(i//2)\n if i % 2 == 0:\n r2 = r1\n else:\n r2 = [0, 0]\n r2[0] = r1[1] * (self.n-1)\n r2[0] %= self.deno\n r2[1] = r1[0] + r1[1] * (self.n-2)\n r2[1] %= self.deno\n \n r = [0, 0]\n r[0] = r1[0] * r2[0] + (self.n-1) * r1[1] * r2[1]\n r[1] = r1[0] * r2[1] + r1[1] * r2[0] + (self.n-2) * r1[1] * r2[1]\n r[0] %= self.deno\n r[1] %= self.deno\n self.mem[i] = r\n return self.mem[i]\n \n def numberOfWays(self, s: str, t: str, k: int) -> int:\n ck = k\n self.deno = 10 ** 9 + 7\n self.n = len(s)\n ms = [31, 47, 59]\n k = len(ms)\n hs = [0] * k\n ht = [0] * k\n muls = [1] * k\n for i in range(self.n):\n ds = ord(s[i])\n dt = ord(t[i])\n if i > 0:\n for j in range(k):\n muls[j] *= ms[j]\n muls[j] %= self.deno\n for j in range(k):\n hs[j] += ds * muls[j]\n hs[j] %= self.deno\n \n ht[j] += dt * muls[j]\n ht[j] %= self.deno\n tht = tuple(ht)\n self.moves = []\n if tuple(hs) == tht:\n self.moves.append(0)\n for i in range(self.n-1):\n ds = ord(s[self.n-1-i])\n for j in range(k):\n hs[j] -= ds * muls[j]\n hs[j] *= ms[j]\n hs[j] += ds\n hs[j] %= self.deno\n if tuple(hs) == tht:\n self.moves.append(i+1)\n #print(self.moves)\n self.mem = {\n 1: [0, 1]\n }\n #print(self.helper(4))\n \n myr = self.helper(ck)\n rst = 0\n for mv in self.moves:\n if mv == 0:\n rst += myr[0]\n else:\n rst += myr[1]\n rst %= self.deno\n \n return rst\n \n \n``` | 0 | 0 | ['Dynamic Programming', 'Python3'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.