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
number-of-substrings-with-only-1s
Java 1 loop O(n)
java-1-loop-on-by-hobiter-z2vw
\n public int numSub(String s) {\n int res = 0, cnt = 0, mod = 1_000_000_007;\n for (char c : s.toCharArray()) {\n if (c == \'1\') r
hobiter
NORMAL
2020-07-12T04:01:17.340759+00:00
2020-07-12T05:57:57.071641+00:00
1,791
false
```\n public int numSub(String s) {\n int res = 0, cnt = 0, mod = 1_000_000_007;\n for (char c : s.toCharArray()) {\n if (c == \'1\') res = (res + ++cnt) % mod; // added cnt of subarrays ended with c;\n else cnt = 0;\n }\n return res;\n }\n```
18
2
[]
4
number-of-substrings-with-only-1s
[Java/Python 3] Count continuous '1's O(n) ONE liner codes w/ brief explanation and analysis.
javapython-3-count-continuous-1s-on-one-accch
For k continuous 1s, we have 1, 2, ..., k substrings ending at 1st, 2nd, ..., kth 1s, respectively; Therefore, there are k * (k + 1) / 2 substrings for any k c
rock
NORMAL
2020-07-12T04:26:12.216352+00:00
2020-07-13T06:29:59.677250+00:00
829
false
For `k` continuous `1`s, we have `1, 2, ..., k` substrings ending at `1st, 2nd, ..., kth 1`s, respectively; Therefore, there are `k * (k + 1) / 2` substrings for any `k` continuous `1`.\n```java\n public int numSub(String s) {\n int sum = 0;\n for (int i = 0, cnt = 0; i < s.length(); ++i) {\n if (s.charAt(i) == \'1\') {\n sum += ++cnt;\n sum %= 1_000_000_007;\n }else {\n cnt = 0;\n }\n }\n return sum;\n }\n```\n```python\n def numSub(self, s: str) -> int:\n sum = cnt = 0\n for c in s:\n if c == \'1\':\n cnt += 1\n sum = (sum + cnt) % (10 ** 9 + 7)\n else:\n cnt = 0\n return sum\n```\n\n----\n**1 liners:**\n```java\n public int numSub(String s) {\n return (int)(Arrays.stream(s.split("0+")).mapToLong(u -> u.length() * (u.length() + 1L) / 2).sum() % 1_000_000_007);\n }\n```\n```python\n def numSub(self, s: str) -> int:\n return sum(map(lambda x : len(x) * (len(x) + 1) // 2, s.split(\'0\'))) % (10 ** 9 + 7)\n```\n\n**Analysis:**\n\nTime: O(n), space: O(1), where n = s.length().
9
0
[]
3
number-of-substrings-with-only-1s
[Python] Sum of Arithmetic Progression with explanation **100.00% Faster**
python-sum-of-arithmetic-progression-wit-m2mf
There is a pattern, you will find that the result is the sum of arithmetic progression.\nArithmetic progression: t(n) = a + d(n-1)\nSum of arithmetic progressio
jasper-w
NORMAL
2020-07-12T04:25:43.226689+00:00
2020-07-12T13:31:01.648360+00:00
1,135
false
There is a ***pattern***, you will find that the ***result is the sum of arithmetic progression***.\nArithmetic progression: **t(n) = a + d(n-1)**\nSum of arithmetic progression: **s(n) = (n / 2) * (2a + d(n-1))**\n\nIn this problem, the first term(a) will be the the length of "1" and the number of terms will also be the length of "1".\n\nThe common difference(d) is **-1**.\n\n**E.g. input is "111111"**\nThen, \n**n = 6\na = 6\nd = -1**\nAfterthat, calculate the sum of arithmetic progression with the formula of **s(n) = (n / 2) * (2a + d(n-1))**,\nCalculate step by step: **(6-0) + (6-1) + (6-2) + (6-3) + (6-4) + (6-5) = 21**,\nwhich is the result of this problem.\n\n***Solution***\n*100% Faster, Memory Usage less than 100.00% of Python3 online submissions.*\n```\nclass Solution:\n def numSub(self, s: str) -> int: \n res = 0\n s = s.split("0")\n\n for one in s:\n if one == "":\n continue\n \n n = len(one)\n temp = (n / 2)*(2*n + (n-1)*-1)\n \n if temp >= 1000000007:\n res += temp % 1000000007\n else:\n res += temp\n return int(res)\n```
8
0
['Python', 'Python3']
2
number-of-substrings-with-only-1s
[C++] Easy math solution
c-easy-math-solution-by-pankajgupta20-55b1
\tclass Solution {\n\tpublic:\n\t\tint numSub(string s) {\n\t\t\tlong count = 0;\n\t\t\tlong ans = 0;\n\t\t\tfor(int i = 0; i < s.size(); i++){\n\t\t\t\tif(s[i
pankajgupta20
NORMAL
2021-05-13T18:36:03.078935+00:00
2021-05-13T18:36:03.078983+00:00
814
false
\tclass Solution {\n\tpublic:\n\t\tint numSub(string s) {\n\t\t\tlong count = 0;\n\t\t\tlong ans = 0;\n\t\t\tfor(int i = 0; i < s.size(); i++){\n\t\t\t\tif(s[i] == \'1\'){\n\t\t\t\t\tcount++;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tans += (count * (count + 1)) / 2;\n\t\t\t\t\tcount = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn (ans + (count * (count + 1)) / 2) % 1000000007;\n\t\t}\n\t};
6
0
['Math', 'C', 'C++']
0
number-of-substrings-with-only-1s
Java, counting, linear time, constant space, explained
java-counting-linear-time-constant-space-4fm5
Algorithm ideas:\neach next consequent 1 contributes to all unique strings with length 1 to k (where k is number of subsequent 1s), k substrings overall. In oth
gthor10
NORMAL
2020-08-11T23:31:56.779214+00:00
2020-08-11T23:31:56.779261+00:00
739
false
Algorithm ideas:\neach next consequent 1 contributes to all unique strings with length 1 to k (where k is number of subsequent 1s), k substrings overall. In other words count of possible substrings increased by k\neach 0 should reset the count of 1s\n\nO(n) time - scan every character in S once\nO(1) space - no extra space\n\n```\n public int numSub(String s) {\n long count = 0;\n int ones = 0;\n \n for (char ch : s.toCharArray()) {\n if (ch == \'0\') {\n ones = 0;\n } else {\n count+=++ones;\n }\n }\n return (int) (count%1_000_000_007);\n }\n```
6
0
['Counting', 'Java']
1
number-of-substrings-with-only-1s
c++, O(n) full beginner friendly explanation!
c-on-full-beginner-friendly-explanation-irsae
Please upvote, if you find the solution helpful !\n\nSolution : \nLogic : We count the number of total number of 1\'s in every substring which contain only 1\'s
h98dubey
NORMAL
2021-06-29T12:34:34.070487+00:00
2021-06-29T12:41:17.821595+00:00
258
false
**Please upvote, if you find the solution helpful !**\n\nSolution : \nLogic : We count the number of total number of 1\'s in every substring which contain only 1\'s.\n\n **Wait, Let me explain!**\n Let\'s take an example : suppose our string is **conscOnes** = "111" i.e. comprising of all 1\'s. \n\nNow, \n**How to calculate the total number of substrings that contains only 1\'s?**\nSimple - we have consider all the substrings, So :-\nThe number of substrings containing only one 1 will be : 3 (i.e. all individual 1\'s)\nThe number of substrings containing two 1\'s will be : 2 (i.e. combining 2 consecutive 1\'s at a time )\nThe number of substrings containing three 1\'s will be : 1(i.e. combining 3 consecutive 1\'s at a time)\nSo, the total number of such substrings would be (3 + 2 + 1 ... in this case). \n\nBut can you see a general pattern ??\nYes, if the size of such a string ( **string conscOnes** ) is **n** then, the number of substrings would be **( n + (n-1) + (n-2) + . . . (1) )** which is = **(n * (n + 1)) / 2 .**\nSo, if we know the number of 1\'s in a **conscOnes** string then we can calculate the number of substrings using the above formula.\n\nNow, our task is reduced to : **find the number of 1\'s** in **every conscOnes string** present in string S, and then we know what to do ! (wink!)\nNow, Do you agree to the fact that, while traversing the string S if a \'1\' is encountered then a new conscOnes string will start and if a \'0\' is encountered the conscOnes string will end.\n\nThat\'s it : as soon as a conscOnes string start we increment a count variable, and as soon as it ends, we add ( count * ( count + 1 ) ) / 2) to our final ans variable.\n \n```\nint numSub(string s) \n {\n\t\t// since the answer can overflow, that\'s why long long int is taken instead of int\n long long int ans = 0, count = 0;\n int mod = 1000000007;\n \n for(int i=0; i<s.size(); i++)\n {\n if(s[i] == \'0\')\n {\n ans += ( (count * (count + 1)) / 2);\n count = 0;\n }\n else\n count++;\n }\n \n ans += ( (count * (count + 1)) / 2);\n \n return ans % mod;\n }
5
0
[]
2
number-of-substrings-with-only-1s
Clean Python 3, counting ones with math O(N)
clean-python-3-counting-ones-with-math-o-owmd
Time: O(N)\nSpace: O(N)\n\nclass Solution:\n def numSub(self, s: str) -> int:\n mod = 10 ** 9 + 7\n seq = (len(ones) for ones in s.split(\'0\')
lenchen1112
NORMAL
2020-07-12T04:02:43.348649+00:00
2020-07-12T04:04:36.032723+00:00
390
false
Time: `O(N)`\nSpace: `O(N)`\n```\nclass Solution:\n def numSub(self, s: str) -> int:\n mod = 10 ** 9 + 7\n seq = (len(ones) for ones in s.split(\'0\') if ones)\n return sum((ones * (ones + 1)) // 2 for ones in seq) % mod\n```
5
0
[]
0
number-of-substrings-with-only-1s
C++ O(n) | Find the pattern
c-on-find-the-pattern-by-nitro-fish-xlc7
\nclass Solution {\npublic:\n int numSub(string s) \n {\n int res=0;\n int i=0;\n while(i<s.size())\n {\n if(s[i]==
nitro-fish
NORMAL
2020-07-12T04:02:06.519450+00:00
2020-07-12T05:35:57.150067+00:00
622
false
```\nclass Solution {\npublic:\n int numSub(string s) \n {\n int res=0;\n int i=0;\n while(i<s.size())\n {\n if(s[i]==\'1\')\n {\n long long count=0;\n while(s[i]==\'1\')\n {\n count++;\n i++;\n }\n count=((count*(count+1))%1000000007)/2; // #substrings in a string of n characters is n*(n+1)/2\n res=(res+count)%1000000007;\n }\n i++;\n }\n return res;\n }\n};\n```\n\nderivation of #substrings in a string of length n\n\nnumber of substrings in "1"=1(1)\nnumber of substrings in "11"=3(1+2)\nnumber of substrings in "111"=6(1+2+3)\nnumber of substrings in "1111"=10(1+2+3+4)\n.\n.\n.\nnumber of substrings in "111....n times"=(1+2+3+...+n=n(n+1)/2)\n\nonce we know this,we can easily find the number of substrings with ony 1s in any string,\n\ns="0110111"\n#substrings in "11"=3\n#substrings in "111"=6\ntotal=3+6=9
5
0
['Math', 'C', 'Sliding Window']
1
number-of-substrings-with-only-1s
TC=O(n), SC=O(1) approach
tcon-sco1-approach-by-anishdhomase-ft9s
Intuition\nTraverse the string and find strings of all ones and by using the formula len*(len+1)/2 find number of strings in which all 1\'s are present and keep
AnishDhomase
NORMAL
2024-03-13T15:18:52.483467+00:00
2024-03-13T15:18:52.483509+00:00
53
false
# Intuition\nTraverse the string and find strings of all ones and by using the formula len*(len+1)/2 find number of strings in which all 1\'s are present and keep adding this answer to our final answer\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int numSub(string s) {\n int i=0, j=0, n=s.length(), mod=1e9+7, ans=0;\n while(i<n && j<n){\n if(s[i]==s[j]) j++;\n else{\n if(s[i]==\'1\'){\n long long l = j-i;\n long long combis = l*(l+1)/2;\n ans = (ans + combis) % mod;\n }\n i=j;\n j++;\n }\n }\n if(s[i]==\'1\'){\n long long l = j-i;\n long long combis = l*(l+1)/2;\n ans = (ans + combis) % mod;\n }\n return ans % mod;\n }\n};\n```
4
0
['C++']
0
number-of-substrings-with-only-1s
ONE-LINER || FASTER THAN 98% || SC 90% ||
one-liner-faster-than-98-sc-90-by-vatsal-3eby
\n return sum(map(lambda x: ((1+len(x))*len(x)//2)%(10**9+7), s.split(\'0\')))\n\nIF THIS HELP U KINDLY UPVOTE THIS TO HELP OTHERS TO GET THIS SOLUTION\n
vatsalg2002
NORMAL
2022-07-20T09:02:20.869679+00:00
2022-07-20T09:02:20.869734+00:00
494
false
```\n return sum(map(lambda x: ((1+len(x))*len(x)//2)%(10**9+7), s.split(\'0\')))\n```\nIF THIS HELP U KINDLY UPVOTE THIS TO HELP OTHERS TO GET THIS SOLUTION\nIF U DONT GET IT KINDLY COMMENT AND FEEL FREE TO ASK\nAND CORRECT MEIF I AM WRONG
4
0
['Python', 'Python3']
3
number-of-substrings-with-only-1s
Easy Java Solution TC:O(n) SC:O(1)
easy-java-solution-tcon-sco1-by-vdb21-x9zv
\n public int numSub(String s) {\n int prev=0;\n int ans=0;\n \n for(int i=0;i<s.length();i++){\n \n if(s.cha
vdb21
NORMAL
2020-12-07T23:36:33.950017+00:00
2020-12-07T23:40:46.823112+00:00
324
false
```\n public int numSub(String s) {\n int prev=0;\n int ans=0;\n \n for(int i=0;i<s.length();i++){\n \n if(s.charAt(i)==\'1\'){\n\t\t\t\t// If current element =1\n prev=prev+1;\n }else{\n\t\t\t\t// If current element =0, reset prev=0\n prev=0;\n }\n ans+=prev;\n ans%=1000000007;\n }\n return ans;\n }\n```
4
0
['Java']
1
number-of-substrings-with-only-1s
[faster than 94%][2 approach][cpp][easy understanding]
faster-than-942-approachcppeasy-understa-fvdm
\n//1.\nclass Solution {\npublic:\n int numSub(string s) {\n int num=0;\n long long count=0;\n for(int i=0;i<s.size();i++){\n
rajat_gupta_
NORMAL
2020-09-16T15:02:53.154314+00:00
2020-09-16T15:02:53.154360+00:00
238
false
```\n//1.\nclass Solution {\npublic:\n int numSub(string s) {\n int num=0;\n long long count=0;\n for(int i=0;i<s.size();i++){\n if(s[i]==\'1\')\n count++;\n else{\n\t\t\t // number of all substrings till n = n * (n+1) / 2 \n count=((count*(count+1)%1000000007)/2);\n num=(num+count)%1000000007;\n count=0;\n } \n }\n\t\t//to handle the edge case\n count=((count*(count+1)%1000000007)/2);\n num=(num+count)%1000000007;\n return num;\n }\n};\n//2.\nclass Solution {\npublic:\n int numSub(string s) {\n int num=0,count=0;\n for(int i=0;i<s.size();i++){\n if(s[i]==\'1\') count++;\n else count=0;\n num=(num+count)%1000000007;\n }\n return num;\n }\n};\n```\n**Feel free to ask any question in the comment section.**\nI hope that you\'ve found the solution useful.\nIn that case, **please do upvote and encourage me** to on my quest to document all leetcode problems\uD83D\uDE03\nHappy Coding :)\n
4
0
['C', 'C++']
1
number-of-substrings-with-only-1s
Just a clever sliding window
just-a-clever-sliding-window-by-slowbutf-yiu0
\nclass Solution {\npublic:\n int numSub(string s) {\n const int m=1000000007;\n int n=s.length();\n int res=0;\n int i=0,j=0;\n
slowbutfast
NORMAL
2020-07-12T07:39:33.655665+00:00
2020-07-12T07:39:33.655716+00:00
332
false
```\nclass Solution {\npublic:\n int numSub(string s) {\n const int m=1000000007;\n int n=s.length();\n int res=0;\n int i=0,j=0;\n while(j<s.length()){\n if(s[j]==\'1\'){\n while(i<j and s[i]!=\'1\')\n i++;\n res=(res%m+(j-i+1)%m)%m;\n }\n else if(s[j]==\'0\')\n i=j;\n j++;\n }\n return res;\n }\n};\n```\n\nWhen you see j pointing to 1 reset i to the starting 1 of the chain.\nand when the chain of one ends reset i to the next zero after the chain of ones.
4
1
[]
3
number-of-substrings-with-only-1s
JAVA | Shortest solution
java-shortest-solution-by-sourin_bruh-hcdr
Please Upvote !!! (\u25E0\u203F\u25E0)\n\nclass Solution {\n public int numSub(String s) {\n int count = 0, total = 0, mod = 1_000_000_007;\n \
sourin_bruh
NORMAL
2022-09-25T13:44:51.781065+00:00
2022-09-25T13:44:51.781101+00:00
883
false
### *Please Upvote !!!* **(\u25E0\u203F\u25E0)**\n```\nclass Solution {\n public int numSub(String s) {\n int count = 0, total = 0, mod = 1_000_000_007;\n \n for (char c : s.toCharArray()) {\n count = (c == \'1\') ? count + 1 : 0;\n total = (total + count) % mod;\n }\n \n return total;\n }\n}\n\n// TC: O(n), SC: O(1)\n```
3
0
['String', 'Java']
0
number-of-substrings-with-only-1s
Java Solution Checking for consecutive One
java-solution-checking-for-consecutive-o-5y2z
Here , I just counted the number of consecutive 1, and updated a counter varibale whenever we encountered with a 1. This varibale actually keep track of consecu
vrohith
NORMAL
2020-09-05T04:05:07.868121+00:00
2020-09-05T04:05:07.868166+00:00
357
false
Here , I just counted the number of consecutive 1, and updated a counter varibale whenever we encountered with a 1. This varibale actually keep track of consecutive 1.\n\nNow we add this count with our result variable. The moment we see a 0, we reset the counter variable back to 0 and again start counting when we see the next 1.\n\n\n\n```\nclass Solution {\n public int numSub(String s) {\n if (s.length() == 0)\n return 0;\n int count = 0;\n int modulus = (int)1e9 + 7;\n int result = 0;\n for (int i=0; i<s.length(); i++) {\n if (s.charAt(i) == \'1\')\n count += 1;\n else\n count = 0;\n result = (result + count) % modulus;\n }\n return result;\n }\n}\n```
3
0
['Java']
0
number-of-substrings-with-only-1s
JavaScript 1-line solution
javascript-1-line-solution-by-sporkyy-0txv
Runtime: 80 ms, faster than 100.00% of JavaScript online submissions\n_Memory Usage: 37.7 MB, less than 100.00% of JavaScript online submissions_\n\njavascript\
sporkyy
NORMAL
2020-07-13T20:48:29.323167+00:00
2020-07-13T20:49:04.600797+00:00
236
false
_Runtime: 80 ms, faster than 100.00% of JavaScript online submissions_\n_Memory Usage: 37.7 MB, less than 100.00% of JavaScript online submissions_\n\n```javascript\nconst numSub = s =>\n s\n .split(\'0\')\n .reduce((cnt, { length: len }) => cnt + (len * (len + 1)) / 2, 0) %\n (10 ** 9 + 7);\n```
3
1
['JavaScript']
0
number-of-substrings-with-only-1s
C++ | O(n)
c-on-by-ashwinfury1-ne8y
Apporach: \narray = [0 1 1 0 1 1 1] , lengths of subarray are 2 and 3\nfor n -> (n* n+1 )/2\n2 -> 3\n3 -> 6\n6+3 = 9\n\nclass Solution {\npublic:\n int numSu
ashwinfury1
NORMAL
2020-07-12T04:19:27.899413+00:00
2020-07-12T04:19:27.899445+00:00
269
false
Apporach: \n``array = [0 1 1 0 1 1 1]`` , lengths of subarray are 2 and 3\nfor n -> (n* n+1 )/2\n2 -> 3\n3 -> 6\n6+3 = 9\n```\nclass Solution {\npublic:\n int numSub(string s) {\n long long ans = 0;\n int mp = 1000000007;\n int n = s.length();\n long long count = 0,i=0;\n while(i<n && s[i] == \'0\') i++;\n if(i==n) return 0;\n for(;i<n;i++){\n if(s[i] == \'1\') count++;\n else{\n ans = (ans % mp + ((count*(count+1))/2 )%mp) % mp;\n count = 0;\n }\n }\n if(count > 0) ans = (ans % mp + ((count*(count+1))/2 )%mp) % mp;\n return ans;\n }\n};\n```
3
0
['C++']
0
number-of-substrings-with-only-1s
[Python3] count continuous "1"
python3-count-continuous-1-by-ye15-rrmo
Algo\nCount number of continuous 1 and use formula n*(n+1)//2 to compute the answer. \n\n\nclass Solution:\n def numSub(self, s: str) -> int:\n ans =
ye15
NORMAL
2020-07-12T04:05:17.970857+00:00
2020-07-12T04:05:17.970902+00:00
258
false
Algo\nCount number of continuous `1` and use formula `n*(n+1)//2` to compute the answer. \n\n```\nclass Solution:\n def numSub(self, s: str) -> int:\n ans = n = 0\n for c in s:\n if c == "0": \n ans = (ans + n*(n+1)//2) % 1_000_000_007\n n = 0\n else: n += 1\n return (ans + n*(n+1)//2) % 1_000_000_007\n```
3
0
['Python3']
0
number-of-substrings-with-only-1s
✅ [Javascript / Python3 / C++] ⭐️ Sum of the Series
javascript-python3-c-sum-of-the-series-b-ob7o
Synopsis:\n\nAccumulate the sum of the series for each run of consecutive 1s length.\n\n---\n\nContest 197 - Screenshare: https://www.youtube.com/watch?v=-oXf4I
claytonjwong
NORMAL
2020-07-12T04:02:54.236807+00:00
2020-08-11T00:42:26.875129+00:00
173
false
**Synopsis:**\n\nAccumulate the sum of the series for each `run` of consecutive 1s length.\n\n---\n\n**Contest 197 - Screenshare:** https://www.youtube.com/watch?v=-oXf4Ikou_c&feature=youtu.be\n\n---\n\n**Solutions:**\n\n*Javascript*\n```\nlet numSub = s => s.split(\'0\').map(run => run.length).reduce((sum, n) => (sum + Math.floor(n * (n + 1) / 2)) % (1e9 + 7), 0);\n```\n\n*Python3*\n```\nclass Solution:\n def numSub(self, s: str) -> int:\n return reduce(lambda sum, n: (sum + (n * (n + 1)) // 2) % int(1e9 + 7), list(map(lambda run: len(run), s.split(\'0\'))), 0)\n```\n\n*C++*\n```\nclass Solution {\npublic:\n using LL = long long;\n using VLL = vector<LL>;\n int numSub(string s, int len = 0, VLL run = {}, int sum = 0) {\n s.push_back(\'0\'); // sentinel value to terminate the last run (if it exists)\n for (auto c: s)\n if (c == \'1\') ++len; else run.push_back(len), len = 0;\n for (auto n: run)\n sum = (sum + (n * (n + 1) / 2)) % LL(1e9 + 7);\n return sum;\n }\n};\n```
3
0
[]
2
number-of-substrings-with-only-1s
sliding window c++ O(n)
sliding-window-c-on-by-jaychadawar-2ug6
IntuitionApproachComplexity Time complexity: Space complexity: Code
JayChadawar
NORMAL
2024-12-18T05:35:35.311916+00:00
2024-12-18T05:35:35.311916+00:00
135
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 {\npublic:\n int numSub(string s) {\n int i=0;\n int j=0;\n int mod=1e9+7;\nint cnt=0;\n while(j<s.size()){\n\n while(s[j]==\'0\'){\n j++;\n }\n i=j;\n while(s[j]==\'1\'){\n cnt=(cnt+j-i+1)%(mod);\n j++;\n }\n\n }\n return cnt;\n\n }\n};\n```
2
0
['Sliding Window', 'C++']
0
number-of-substrings-with-only-1s
Easy Python solution
easy-python-solution-by-chandan_giri-mxp8
Intuition\n Describe your first thoughts on how to solve this problem. \nCount the number of 1 in each substring of 1s.\nApply (N(N+1))//2 after the end of each
Chandan_Giri
NORMAL
2024-05-22T11:35:13.811973+00:00
2024-05-22T11:35:13.812003+00:00
85
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCount the number of 1 in each substring of 1s.\nApply (N(N+1))//2 after the end of each 1s substring.\nExample:\ns = "0110111"\nHere we have 2 substring of 1 in this example. \n1st has 2 ones and 2nd has 3 ones.\nso ans = (2*(2+1))//2 + (3*(3+1))//2 \nreturn ans % (10**9+7)\n# Approach\n<!-- Describe your approach to solving the problem. -->\nInitialize count and ans = 0.\nTraverse the string for each index and check \nif s[index] == "1" --> increment the value of count.\nelse calculate the value of (n*(n+1))//2 and add it to the ans, set count = 0.\nAfter traversing the string for last substring if count > 0 then again calculate the value of (n*(n+1))//2 and add it to the ans.\nreturn ans % (10**9+7)\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def numSub(self, s: str) -> int:\n ans = 0\n count = 0\n for i in s:\n if i == "1":\n count += 1\n else:\n temp = (count*(count+1))//2\n ans += temp\n count = 0\n if count > 0:\n temp = (count*(count+1))//2\n ans += temp\n return ans%(10**9+7)\n```
2
0
['Python3']
0
number-of-substrings-with-only-1s
O (1) Space | Intuitive explanation | C++, Python, Java
o-1-space-intuitive-explanation-c-python-n1pt
Intuition\n Describe your first thoughts on how to solve this problem. \n\nThe solution works by keeping track of consecutive \'1\' sequences and calculating th
1227hariharan
NORMAL
2024-01-19T12:35:28.302675+00:00
2024-01-19T12:35:28.302706+00:00
532
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThe solution works by keeping track of consecutive \'**1**\' sequences and calculating the count of valid substrings for each sequence. The formula c*(c+1)/2 calculates the sum of an arithmetic series for each sequence. This is based on the fact that if there are **C** consecutive \'**1**\'s, the number of valid substrings ending at the last \'**1**\' in the sequence is given by the sum of the first **C** natural numbers.\n\n\n![image.png](https://assets.leetcode.com/users/images/0902ac6c-9144-428f-892d-21b4b047988b_1705665559.6872487.png)\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nInitiate a variable **C** to store the length of consecutive **1s**. Iterate through the array. In each iteration, there are two possible outcomes:\n\n- The current element is **1**, and it belongs to a sequence of continuous **1s**.\n- The current element is **0**, and possibly a sequence of **1s** may have terminated just before it.\n\nSo, iterate through the array. If the current element is **1**, increment **C**. Otherwise, calculate the number of subarrays for the previous sequence of **1s** (using n * (n + 1) / 2) and reset the value of **C** to 0\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n\n```Python []\nclass Solution:\n def numSub(self, s: str) -> int:\n\n c = 0\n ans = 0\n for item in s:\n if item == \'1\':\n c += 1\n else:\n ans += c*(c+1)//2\n c = 0\n else:\n ans += c*(c+1)//2\n\n \n return ans % (10**9+7)\n```\n```Java []\nclass Solution {\n public int numSub(String s) {\n long c = 0,ans = 0,l =1000000007L ;\n\n\n for(int i = 0; i < s.length(); i++){\n Character ch = s.charAt(i);\n if(ch == \'1\'){\n c ++;\n }else{\n ans += c*(c+1)/2;\n c=0;\n }\n }\n \n ans += c*(c+1)/2;\n return (int) (ans % (Math.pow(10, 9) + 7));\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int numSub(string s) {\n \n long long c = 0,ans = 0;\n for(auto ch : s){\n if(ch == \'1\'){\n c ++;\n }else{\n ans += c*(c+1)/2;\n c=0;\n }\n }\n\n ans += c*(c+1)/2;\n return ans%1000000007;\n\n }\n};\n\n```\n\n\n\n
2
0
['C++', 'Java', 'Python3']
0
number-of-substrings-with-only-1s
Simple easy solution, 2 methods ✅✅
simple-easy-solution-2-methods-by-vaibha-dbbg
\n\n# Complexity\n- Time complexity: O(N)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n
vaibhav2112
NORMAL
2023-11-09T13:15:41.490013+00:00
2023-11-09T13:15:41.490062+00:00
581
false
\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int numSub(string s) {\n // int i = 0, n = s.length(), ans = 0 , mod = 1e9 + 7;\n // while(i<n){\n // if(s[i] == \'0\'){\n // i++;\n // }\n // else{\n // char x = s[i];\n // long long cnt = 0;\n // while(i<n && x == s[i]){\n // cnt++;\n // i++;\n // }\n // ans = (ans + (cnt*(cnt+1))/2)%mod;\n // }\n \n // }\n // return ans;\n\n int i = 0, j = 0, ans = 0, n = s.length();\n int mod = 1e9 + 7;\n\n while(j<n){\n if(s[i] == \'0\'){\n j++;\n i = j;\n }\n else{\n if(s[i] == s[j]){\n ans = (ans + (j-i+1))%mod;\n j++;\n }\n else{\n i = j;\n }\n }\n }\n return ans;\n }\n};\n```
2
0
['C++']
0
number-of-substrings-with-only-1s
TypeScript - Math
typescript-math-by-amal-ps-xt0q
Code\n\nfunction numSub(s) {\n let count = 0;\n let permuSum = 0;\n for (let i = 0; i < s.length; i++) {\n if (s[i] == \'1\') {\n cou
amal-ps
NORMAL
2023-08-16T10:54:40.627428+00:00
2023-08-16T10:54:40.627453+00:00
6
false
# Code\n```\nfunction numSub(s) {\n let count = 0;\n let permuSum = 0;\n for (let i = 0; i < s.length; i++) {\n if (s[i] == \'1\') {\n count = count + 1;\n } else {\n permuSum = (permuSum + permutation(count)) % (10 ** 9 + 7);\n count = 0;\n }\n }\n permuSum = (permuSum + permutation(count)) % (10 ** 9 + 7);\n return permuSum;\n}\n\nfunction permutation(n) {\n return (n * (n + 1) / 2) % (10 ** 9 + 7);\n}\n\n```
2
0
['Math', 'TypeScript']
0
number-of-substrings-with-only-1s
Beats 90% CPP SOL ✅✅
beats-90-cpp-sol-by-zenitsu02-xchn
Pls Upvote if you found it Helpful \uD83D\uDE07\n# Complexity\n- Time complexity: O(N)\n\n- Space complexity: O(1)\n\n# Code\n\nclass Solution {\npublic:\n i
Zenitsu02
NORMAL
2023-07-26T14:25:18.544795+00:00
2023-07-26T14:25:18.544827+00:00
219
false
# **Pls Upvote if you found it Helpful \uD83D\uDE07**\n# Complexity\n- Time complexity: O(N)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution {\npublic:\n int mod = 1e9 + 7;\n int numSub(string s) {\n\n int front = 0;\n int back = 0;\n int ans = 0;\n\n while(front < s.size()){\n while(front<s.size() && s[front] != \'1\'){\n front++;\n }\n back = front;\n while(front<s.size() && s[front] == \'1\'){\n ans = ans + (front-back+1);\n ans = ans % mod;\n front++;\n }\n }\n\n return ans;\n }\n};\n```
2
0
['Sliding Window', 'Iterator', 'C++']
0
number-of-substrings-with-only-1s
EASY TO UNDERSTAND C++ SOLUTION
easy-to-understand-c-solution-by-abhay_1-udti
\nclass Solution {\npublic:\n int numSub(string s) {\n long long int ans = 0, i = 0, j= 0, n = s.length(),mod = 1e9+7;\n while(i<n){\n
abhay_12345
NORMAL
2022-11-19T07:21:19.154328+00:00
2022-11-19T07:21:19.154366+00:00
420
false
```\nclass Solution {\npublic:\n int numSub(string s) {\n long long int ans = 0, i = 0, j= 0, n = s.length(),mod = 1e9+7;\n while(i<n){\n j = i;\n while(j<n && s[i] == s[j]){\n j++;\n if(s[i]==\'1\'){\n ans = (ans+j-i)%mod;\n }\n }\n i = j;\n }\n return ans;\n }\n};\n```
2
0
['Math', 'C', 'C++']
0
number-of-substrings-with-only-1s
Sum of N numbers, Python
sum-of-n-numbers-python-by-antarab-wmar
Basically, the no. of consecutions \'1\'s can form n*(n+1)//2 substrings\n11 -> 2 1s, 1 2s = 2+1\n111 -> 3 1s, 2 2s, 1 3s = 3+2+1\n1111 -> 4 1s, 3 2s, 2 3s, 1 4
antarab
NORMAL
2022-10-26T22:32:08.799661+00:00
2022-10-26T22:32:08.799700+00:00
357
false
Basically, the no. of consecutions \'1\'s can form n*(n+1)//2 substrings\n11 -> 2 1s, 1 2s = 2+1\n111 -> 3 1s, 2 2s, 1 3s = 3+2+1\n1111 -> 4 1s, 3 2s, 2 3s, 1 4s = 4+3+2+1\n\n```\n def numSub(self, s: str) -> int:\n c=0\n ans=[]\n for x in s:\n if x==\'1\':\n c=c+1\n else:\n ans.append(c)\n c=0\n ans.append(c)\n \n res=0\n for x in ans:\n res=res+x*(x+1)//2\n return res%1000000007\n```\n
2
0
[]
0
number-of-substrings-with-only-1s
Go 2ms beats 100%
go-2ms-beats-100-by-tuanbieber-7x1g
\nfunc numSub(s string) int {\n\tif len(s) == 0 {\n\t\treturn 0\n\t}\n\n\tif len(s) == 1 {\n\t\tif s[0] == 49 {\n\t\t\treturn 1\n\t\t}\n\n\t\treturn 0\n\t}\n\n\
tuanbieber
NORMAL
2022-06-22T03:03:08.200831+00:00
2022-06-22T03:03:08.200874+00:00
161
false
```\nfunc numSub(s string) int {\n\tif len(s) == 0 {\n\t\treturn 0\n\t}\n\n\tif len(s) == 1 {\n\t\tif s[0] == 49 {\n\t\t\treturn 1\n\t\t}\n\n\t\treturn 0\n\t}\n\n\tleft := 0\n\n for left < len(s) && s[left] != 49 {\n\t\tleft++\n\t}\n\n\tvar res int\n\n\tfor i := left; i < len(s); i++ {\n\t\tif s[i] == s[left] {\n\t\t\tcontinue\n\t\t} else {\n\t\t\tif s[i] == 48 {\n\t\t\t\tres += helper(i - left)\n\t\t\t}\n\n\t\t\tleft = i\n\t\t}\n\t}\n\n if left < len(s) && s[left] == 49 {\n\t\tres += helper(len(s) - left)\n\t}\n\n\treturn res % (int(math.Pow10(9)) + 7)\n}\n\nfunc helper(length int) int {\n\tif length < 2 {\n\t\treturn length\n\t}\n\n\tvar res int\n\n\tfor i := 1; i < length; i++ {\n\t\tres += length - i\n\t}\n\n\treturn res + length\n}\n\n\n```
2
0
['Go']
1
number-of-substrings-with-only-1s
C++ Simple Solution
c-simple-solution-by-chirags_30-1jdy
\nclass Solution {\npublic:\n int numSub(string s) \n {\n int ans=0, count=0;\n for(auto c:s)\n {\n if(c == \'0\')\n
chirags_30
NORMAL
2021-05-30T11:29:11.570499+00:00
2021-05-30T11:29:11.570541+00:00
101
false
```\nclass Solution {\npublic:\n int numSub(string s) \n {\n int ans=0, count=0;\n for(auto c:s)\n {\n if(c == \'0\')\n ans=0;\n \n else\n {\n ans++;\n count = (count+ans)%(1000000007);\n }\n }\n return count;\n }\n};\n```
2
2
['Math', 'C', 'C++']
0
number-of-substrings-with-only-1s
[JavaScript] easy to understand solution (61%,83%)
javascript-easy-to-understand-solution-6-k537
Runtime: 88 ms, faster than 61.70% of JavaScript online submissions for Number of Substrings With Only 1s.\nMemory Usage: 40.2 MB, less than 87.23% of JavaScrip
0533806
NORMAL
2021-05-23T09:59:40.310074+00:00
2021-05-23T10:08:16.739152+00:00
152
false
Runtime: 88 ms, faster than 61.70% of JavaScript online submissions for Number of Substrings With Only 1s.\nMemory Usage: 40.2 MB, less than 87.23% of JavaScript online submissions for Number of Substrings With Only 1s.\n```\nvar numSub = function(s) {\n let res = 0;\n let one = 0;\n for(let num of s){\n if(num==="1") one++, res+=one;\n else one = 0;\n }\n return res%1000000007;\n};\n```
2
0
['JavaScript']
0
number-of-substrings-with-only-1s
Python solution one-pass
python-solution-one-pass-by-flyingspa-jd5x
class Solution:\n\n def numSub(self, s: str) -> int:\n ans = cum = 0\n for x in s:\n if x == "1":\n cum+=1\n
flyingspa
NORMAL
2021-03-26T10:50:58.049651+00:00
2021-03-26T10:50:58.049677+00:00
126
false
class Solution:\n\n def numSub(self, s: str) -> int:\n ans = cum = 0\n for x in s:\n if x == "1":\n cum+=1\n ans+=cum\n else:\n cum = 0\n return ans%(10**9+7)
2
0
['Python']
0
number-of-substrings-with-only-1s
Python One Liner
python-one-liner-by-ragav_1302-l65h
\nclass Solution:\n def numSub(self, s: str) -> int:\n return sum(map(lambda i:(len(i)*(len(i)+1))//2,re.findall("[1]+",s)))%(10**9+7)\n
ragav_1302
NORMAL
2020-11-16T10:13:45.017237+00:00
2020-11-16T10:13:45.017271+00:00
108
false
```\nclass Solution:\n def numSub(self, s: str) -> int:\n return sum(map(lambda i:(len(i)*(len(i)+1))//2,re.findall("[1]+",s)))%(10**9+7)\n```
2
1
[]
0
number-of-substrings-with-only-1s
CPP ⭐ 8ms ⭐ Reason for using mod...
cpp-8ms-reason-for-using-mod-by-daranip-pavi
%(mod) 1000000007 is used because it prevents overflow and enables the problem setter to frame his problem for bigger ranges and hence demand a clever algorithm
daranip
NORMAL
2020-10-17T17:02:31.332020+00:00
2020-10-18T08:10:04.227697+00:00
134
false
**%(mod) 1000000007** is used because it prevents overflow and enables the problem setter to frame his problem for bigger ranges and hence demand a clever algorithm.\n\n```\nclass Solution {\npublic:\n long numSub(string s) {\n long i=0,temp = 0,total=0;\n while (i<s.length()){\n if (s[i]==\'1\'){\n temp = 0;\n while (s[i]==\'1\'){\n temp++;\n i++;\n }\n total += (temp*(temp+1))/2;\n }\n i++;\n }\n return total%1000000007; // to prevent overflow\n }\n};\n```
2
1
[]
1
number-of-substrings-with-only-1s
8ms faster than 80% submissions.
8ms-faster-than-80-submissions-by-varnaa-f8lr
\nclass Solution {\n public int numSub(String s) {\n int count = 0;\n String[] ones = s.split("0");\n for(String one : ones){\n
varnaa
NORMAL
2020-07-28T06:33:45.627660+00:00
2020-07-28T06:33:45.627694+00:00
102
false
```\nclass Solution {\n public int numSub(String s) {\n int count = 0;\n String[] ones = s.split("0");\n for(String one : ones){\n int len = one.length();\n if(len >= 1)\n count += (len*(len+1.0)/2) % 1000000007;\n }\n \n return count;\n }\n}\n```
2
1
['Java']
1
number-of-substrings-with-only-1s
C++ | Simple O(n) DP Solution
c-simple-on-dp-solution-by-draco7leetcod-389f
DP[i]=for every \'1\' encountered at ith position, the number of substrings that can be formed will be equal to the number of substrings formed at (i-1)th posit
draco7leetcode
NORMAL
2020-07-14T18:07:41.500718+00:00
2020-07-14T18:13:15.786571+00:00
67
false
DP[i]=for every \'1\' encountered at **ith position, the number of substrings that can be formed will be equal to the number of substrings formed at (i-1)th position +1.** \nAt last , the total number of substrings can be found by adding all the values of DP array.\nPS:- I know , this problem can be done without dp approach, but still its better to visualize a problem thorugh it apart from n*(n+1)/2 method.. (pls upvote if you agree) :)\n```\nint numSub(string s) {\n long i=0,j=0,n=s.length();\n long dp[n];\n dp[0]=(s[0]==\'0\')?0:1;\n \n int sum=dp[0];\n for(long i=1;i<n;i++){\n if(s[i]==\'1\')\n dp[i]=1+dp[i-1];\n else\n dp[i]=0;\n \n sum=(sum+dp[i])%1000000007;\n }\n return sum;\n }\n```
2
0
['Dynamic Programming', 'C']
0
number-of-substrings-with-only-1s
Easy count and sum javascript solution
easy-count-and-sum-javascript-solution-b-fy91
\nvar numSub = function(s) {\n let result = 0;\n let len = 0; \n \n for (let i = 0; i < s.length; ++i) {\n if (s[i] === "1") {\n
eforce
NORMAL
2020-07-12T07:33:39.358680+00:00
2020-07-12T07:33:39.358728+00:00
70
false
```\nvar numSub = function(s) {\n let result = 0;\n let len = 0; \n \n for (let i = 0; i < s.length; ++i) {\n if (s[i] === "1") {\n len++;\n result += len;\n } else {\n len = 0;\n }\n }\n \n return result % 1000000007;\n};\n```
2
0
[]
0
number-of-substrings-with-only-1s
C++| Step by Step Explanation | O(n)
c-step-by-step-explanation-on-by-sumanth-bd2p
Find length of each substring containing only 1\'s.\nOnce we find a substring of length l with only 1\'s no. of substrings possible is given by l(l+1)/2 (sum of
sumanthspark10
NORMAL
2020-07-12T06:23:56.568034+00:00
2020-08-01T06:20:51.066148+00:00
161
false
Find length of each substring containing only 1\'s.\nOnce we find a substring of length l with only 1\'s no. of substrings possible is given by l*(l+1)/2 (sum of numbers from 1 to l)\nExample - 110111\nThere are two substrings containing only 1\'s..i.e., 11 of length 2 and 111 of length 3\nFor 1st substring "11" -\nNo. of substring which Contain \'1\' is - 2\nNo. of substring which Contain \'11\' is - 1\n\nTotal No. of substring =2+1 = 2*(2+1)/2 = 3\n\nFor 1st substring "111" -\nNo. of substring which Contain \'1\' is - 3\nNo. of substring which Contain \'11\' is - 2\nNo. of substring which Contain \'111\' is - 1\n\nTotal No. of substring =3+2+1 = 2=3*(3+1)/2 = 6\n\nSo. total no. of substrings aren 3+6 = 9\n\n```\nclass Solution {\npublic:\n long long int total(int n){\n long long int res=0;\n for(int i=1;i<=n;i++){\n res+=i;\n }\n return res;\n }\n int numSub(string s) {\n long long int ans = 0;\n for(int i=0;i<s.length();i++){\n int l =0;\n if(s[i]==\'1\'){\n l++;\n while(i+1<s.length() && s[i+1]!=\'0\'){\n l++;\n i++;\n }\n }\n ans+=total(l);\n }\n return ans%1000000007;\n }\n};\n```
2
1
['C', 'C++']
0
number-of-substrings-with-only-1s
C# Solution
c-solution-by-leonhard_euler-l4w7
\npublic class Solution \n{\n public int NumSub(string s) \n {\n long prev = -1, result = 0, n = s.Length;;\n for(int i = 0; i <= n; i++)\n
Leonhard_Euler
NORMAL
2020-07-12T04:49:35.714127+00:00
2020-07-12T04:49:35.714160+00:00
67
false
```\npublic class Solution \n{\n public int NumSub(string s) \n {\n long prev = -1, result = 0, n = s.Length;;\n for(int i = 0; i <= n; i++)\n if(i == n || s[i] == \'0\')\n {\n long len = (i - prev - 1);\n result += (len * (len + 1)) / 2;\n result = result % 1_000_000_007;\n prev = i;\n }\n \n return (int) result;\n }\n}\n```
2
0
[]
0
number-of-substrings-with-only-1s
[Python] Easy understand solution
python-easy-understand-solution-by-too-y-d1jg
\nclass Solution(object):\n def numSub(self, s):\n """\n :type s: str\n :rtype: int\n """\n res = 0\n arr = s.split
too-young-too-naive
NORMAL
2020-07-12T04:11:14.343544+00:00
2020-07-12T04:11:14.343597+00:00
59
false
```\nclass Solution(object):\n def numSub(self, s):\n """\n :type s: str\n :rtype: int\n """\n res = 0\n arr = s.split("0")\n for i in arr:\n n = len(i)\n if n == 0:\n continue\n res += n*(n+1)/2\n res = res % (10**9 + 7)\n return res\n```
2
0
[]
0
number-of-substrings-with-only-1s
Single-line solution, beats 100%
single-line-solution-beats-100-by-simole-w9ub
Code
simolekc
NORMAL
2025-02-14T06:19:46.242261+00:00
2025-02-14T06:19:46.242261+00:00
27
false
# Code ```javascript [] /** * @param {string} s * @return {number} */ var numSub = function (s) { const mod = 10 ** 9 + 7; return ( s .split("0") .reduce( (sum, str) => sum + (Boolean(str) ? ((str.length * (str.length + 1)) / 2) % mod : 0), 0 ) % mod ); }; ```
1
0
['JavaScript']
0
number-of-substrings-with-only-1s
Java || Detailed Explanation
java-formula-for-substrings-by-ritabrata-zqqp
IntuitionFormula for number of substrings of a given string on length n, is n*(n+1)/2ApproachCalculate length of substrings containing only 1 and apply the form
Ritabrata_1080
NORMAL
2025-01-09T19:22:39.159223+00:00
2025-01-09T19:25:27.336938+00:00
100
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Formula for number of substrings of a given string on length n, is n*(n+1)/2 # Approach <!-- Describe your approach to solving the problem. --> Calculate length of substrings containing only 1 and apply the formula for finding the number of substrings for that particular substring. Keep adding the number of substrings in a result variable and return that. ## Note The final result should be of long type (In java). I got Wrong Answer in 54th test case if result is stored in Integer. # Result ![WhatsApp Image 2025-01-10 at 00.48.40.jpeg](https://assets.leetcode.com/users/images/806140d4-7f6e-4114-abaa-ca81ef0e1d35_1736450525.8098552.jpeg) # Code ```java [] class Solution { public int numSub(String s) { long count = 0, res = 0; for(char c : s.toCharArray()){ if(c == '1'){ //System.out.println("hit"); count++; } else { //System.out.println(count); res += (count*(count+1))/2; count = 0; } } res = res % 1_000_000_007; return (count == 0) ? (int)res : (int)(res += (count*(count+1))/2); } } ``` # Please upvote the solution if you find it helpful Cheers :-)
1
0
['Java']
0
number-of-substrings-with-only-1s
JAVA O(N) solution | Count | String | Math | Good Readability | Beginners Friendly
java-on-solution-count-string-math-good-uub36
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
karan_s01
NORMAL
2024-08-26T10:08:50.015895+00:00
2024-08-26T10:08:50.015919+00:00
39
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- Space complexity : O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# Code\n```java []\nclass Solution {\n public int numSub(String s) {\n long count = 0;\n long ones = 0;\n long mod = 1_000_000_007;\n for (int i=0 ; i<s.length() ; i++){\n if (s.charAt(i) == \'1\'){\n ones++;\n }\n if(i == s.length()-1 || s.charAt(i) == \'0\'){\n count += ones*(ones+1)/2;\n ones = 0;\n }\n }\n return (int)(count%mod);\n }\n}\n```\n- Guys dont forget to upvote
1
0
['Math', 'String', 'Java']
0
number-of-substrings-with-only-1s
Easy JS Solution with Tips to watch out for
easy-js-solution-with-tips-to-watch-out-a8lnt
Intuition\n Describe your first thoughts on how to solve this problem. \nSimply apply the formula to the no, of occurances on the group.\n# Approach\n Describe
giogokul13
NORMAL
2024-03-30T12:49:54.661003+00:00
2024-03-30T12:49:54.661061+00:00
16
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSimply apply the formula to the no, of occurances on the group.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nArears to Watch out;\n* Loop untill the last + 1 element, as we need to calculate all the occurance of once\n* Reset the one counter once the calculation is done\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {string} s\n * @return {number}\n */\nvar numSub = function (s) {\n let result = 0;\n let oneCounter = 0;\n const MODULO = 10 ** 9 + 7;\n for (let i = 0; i <= s.length; i++) {\n if (s[i] == "1") {\n oneCounter++;\n } else {\n result = (result + (oneCounter + 1) * oneCounter / 2) % MODULO\n oneCounter = 0;\n }\n }\n\n return result;\n};\n```
1
0
['JavaScript']
0
number-of-substrings-with-only-1s
Simple java code for beginners
simple-java-code-for-beginners-by-arobh-z3st
\n# Complexity\n- \n\n# Code\n\nclass Solution {\n public int numSub(String s) {\n int n=s.length();\n int count=0;\n int mod=1000000007
Arobh
NORMAL
2023-12-30T12:15:45.448736+00:00
2023-12-30T12:15:45.448814+00:00
77
false
\n# Complexity\n- \n![image.png](https://assets.leetcode.com/users/images/73f18eef-6a02-40d7-8225-d54ed86ca041_1703938542.179247.png)\n# Code\n```\nclass Solution {\n public int numSub(String s) {\n int n=s.length();\n int count=0;\n int mod=1000000007;\n int i=0,j=0;\n while(j<n){\n if(s.charAt(i)==\'0\'){\n j++;\n i=j;\n }\n else{\n if(s.charAt(i)==s.charAt(j)){\n count=(count+(j-i+1))%mod;\n j++;\n }\n else{\n i=j;\n }\n }\n }\n return count;\n }\n}\n```
1
0
['Java']
0
number-of-substrings-with-only-1s
Easy C++ solution in O(N)
easy-c-solution-in-on-by-sachin_kumar_sh-mk5z
Intuition\nJust keep the count of number of 1s in the given string.\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nTraverse the gi
Sachin_Kumar_Sharma
NORMAL
2023-12-09T07:28:22.254611+00:00
2023-12-09T07:28:22.254659+00:00
2
false
# Intuition\nJust keep the count of number of 1s in the given string.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nTraverse the given string and keep on incrementing the cnt when we encounter 1. \nAnd the update the ans by adding the cnt to it.\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(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int numSub(string s) {\n int i,ans=0,cnt=0;\n const int MOD=1e9+7;\n\n for(auto ch: s){\n if(ch==\'1\'){\n cnt++;\n ans=(ans+cnt)%MOD;\n }\n else{\n cnt=0;\n }\n }\n\n return ans;\n }\n};\n```
1
0
['C++']
0
number-of-substrings-with-only-1s
C++ || Sliding Window || Easy to Understand
c-sliding-window-easy-to-understand-by-m-74zl
Intuition\n Describe your first thoughts on how to solve this problem. \n1. Initialization: Start and end are initialized to the beginning of the string. totalS
Mohd_Nasir
NORMAL
2023-11-09T04:50:23.538171+00:00
2023-11-09T04:50:23.538193+00:00
366
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. **Initialization**: Start and end are initialized to the beginning of the string. `totalSubStrings` is the count of valid substrings, initialized to 0.\n2. **Traversal through the string**: The code iterates through each character of the string.\n3. **Handling \'0\'**: If the current character is \'0\', it means the current substring cannot be extended. So, move the start pointer to the next character and continue the loop.\n4. **Counting valid substrings**: If the current character is \'1\', it contributes to forming valid substrings. The code calculates the number of valid substrings ending at the current position and updates the total count.\n5. **Modular arithmetic**: To avoid integer overflow, the code uses modular arithmetic by taking the result modulo `1e9 + 7`.\n6. **Moving the end pointer**: After processing the current character, the end pointer is moved to the next character.\n7. **Repeat**: Steps 3-6 are repeated until the end of the string is reached.\n8. **Final result**: The function returns the total count of valid substrings.\n\nIn essence, the algorithm counts the number of continuous substrings of \'1\'s in the binary string and handles \'0\'s by resetting the start pointer. The use of modular arithmetic ensures that the result stays within reasonable bounds.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Two Pointers (start and end):**\n - The algorithm uses two pointers, `start` and `end`, to traverse the string and identify substrings.\n2. **Traversal through the String:**\n - The algorithm iterates through each character of the input string.\n3. **Handling \'0\'s:**\n - If the current character is \'0\', it means the current substring cannot be extended. Therefore, the `start` pointer is moved to the next character, and the loop continues.\n4. **Counting Valid Substrings:**\n - If the current character is \'1\', it contributes to forming valid substrings. The algorithm calculates the number of valid substrings ending at the current position and updates the total count.\n5. **Modular Arithmetic:**\n - To avoid integer overflow, the algorithm uses modular arithmetic (`MOD = 1e9 + 7`) by taking the result modulo `MOD`.\n6. **Moving the End Pointer:**\n - After processing the current character, the `end` pointer is moved to the next character, continuing the traversal.\n7. **Repeat Until End of String:**\n - Steps 3-6 are repeated until the end of the string is reached.\n8. **Final Result:**\n - The function returns the total count of valid substrings.\n\nThe overall approach focuses on efficiently counting the number of continuous substrings of \'1\'s in the binary string while handling \'0\'s appropriately and using modular arithmetic for numerical stability.\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n // Define a constant for modular arithmetic\n const int MOD = 1e9 + 7;\n\n // Function to count the number of valid substrings in a binary string\n int numSub(string s) {\n // Initialize start and end pointers\n int start = 0, end = 0;\n\n // Get the length of the input string\n int len = s.length();\n\n // Variable to store the total number of valid substrings\n int totalSubStrings = 0;\n\n // Loop through the characters of the string\n while(end < len){\n // If the current character is \'0\', move the start pointer\n // to the next character and continue to the next iteration\n if(s[end] == \'0\'){\n end += 1;\n start = end;\n continue;\n }\n\n // Calculate the number of valid substrings ending at the current position\n totalSubStrings += ((end - start + 1) % MOD);\n totalSubStrings %= MOD;\n \n // Move the end pointer to the next character\n end += 1;\n }\n\n // Return the total number of valid substrings\n return totalSubStrings;\n }\n};\n\n```
1
0
['Math', 'String', 'Sliding Window', 'C++']
0
number-of-substrings-with-only-1s
Very Easy to understand C++ || Easiest of all time
very-easy-to-understand-c-easiest-of-all-aq81
\n\n# Code\n\nclass Solution {\npublic:\n const int mod=1e9+7;\n\n int numSub(string s) {\n long long ans=0;\n for(long long i=0;i<s.size();
Sakettiwari
NORMAL
2023-10-26T21:41:37.589723+00:00
2023-10-26T21:41:37.589748+00:00
20
false
\n\n# Code\n```\nclass Solution {\npublic:\n const int mod=1e9+7;\n\n int numSub(string s) {\n long long ans=0;\n for(long long i=0;i<s.size();i++){\n if(s[i] == \'0\')\n continue;\n else{\n long long j;\n for( j=i;j<s.size();j++){\n if(s[j] == \'0\')\n break;\n ans+=j-i+1;\n \n }\n i=j;\n }\n }\n \n return ans%mod;\n }\n};\n```
1
0
['C++']
1
number-of-substrings-with-only-1s
Simple C++ solution
simple-c-solution-by-gcsingh1629-qsg5
\n# Code\n\nclass Solution {\npublic:\n int numSub(string s) {\n int left=0,count=0,res=0,mod=1e9+7;\n for(int right=0;right<s.size();right++){
gcsingh1629
NORMAL
2023-10-08T06:54:04.112308+00:00
2023-10-08T06:54:04.112328+00:00
80
false
\n# Code\n```\nclass Solution {\npublic:\n int numSub(string s) {\n int left=0,count=0,res=0,mod=1e9+7;\n for(int right=0;right<s.size();right++){\n if(s[right]==\'1\'){\n count++;\n res=(res+count)%mod;\n }\n else{\n count=0;\n }\n }\n return res;\n }\n};\n```
1
0
['C++']
1
number-of-substrings-with-only-1s
Super Easy Accumulator Approach
super-easy-accumulator-approach-by-sheve-2wfg
Approach\nWe iterate over all chars in string.\nIf character is 1, we increment our accuumulator by 1.\nThen we add accumulator to total result amount.\nThats b
shevernitskiy
NORMAL
2023-08-22T13:23:31.061085+00:00
2023-08-22T13:23:31.061116+00:00
8
false
# Approach\nWe iterate over all chars in string.\nIf character is 1, we increment our accuumulator by 1.\nThen we add accumulator to total result amount.\nThats beacuse in `1` there is 1 variant, then in `11` there are 3 variants (1, 1, 11), but the first `1` we already count on previous step. So just increment accumulator and add it to result (+2).\nIn case of 0 we only reset accumulator to 0.\n\n# Code\n```\n\tfunction numSub(s: string): number {\n\t\tlet amount = 0;\n\t\tlet count = 0;\n\n\t\tfor (let i = 0; i < s.length; i++) {\n\t\t\tif (s[i] === "0" && amount > 0) {\n\t\t\t\tamount = 0;\n\t\t\t}\n\t\t\tif (s[i] === "1") {\n\t\t\t\tamount++;\n\t\t\t\tcount += amount;\n\t\t\t}\n\t\t}\n\n\t\treturn count % (10 ** 9 + 7);\n\t}\n```
1
0
['TypeScript']
0
number-of-substrings-with-only-1s
Easy to understand JavaScript solution
easy-to-understand-javascript-solution-b-2t1t
Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n\nvar numSub = function(s) {\n const MODULO = 10 ** 9 + 7;\n let current = re
tzuyi0817
NORMAL
2023-08-06T08:01:40.198340+00:00
2023-08-06T08:01:40.198365+00:00
14
false
# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nvar numSub = function(s) {\n const MODULO = 10 ** 9 + 7;\n let current = result = 0;\n\n for (let index = 0; index <= s.length; index++) {\n const value = s[index];\n\n if (value === \'1\') current += 1;\n else {\n result = (result + (current + 1) * current / 2) % MODULO;\n current = 0;\n }\n }\n return result;\n};\n```
1
0
['JavaScript']
0
number-of-substrings-with-only-1s
✅✔️Easy Peasy Implementation || C++ Solution ✈️✈️✈️✈️✈️
easy-peasy-implementation-c-solution-by-upbtj
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
ajay_1134
NORMAL
2023-07-13T05:50:12.760940+00:00
2023-07-13T05:50:12.760964+00:00
186
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:\n int numSub(string s) {\n int n = s.length(), mod = 1e9+7;\n int cnt = 0;\n long long ans = 0;\n for(int i=0; i<n; i++){\n if(s[i] == \'1\'){\n cnt++;\n ans += cnt;\n ans = ans%mod;\n }\n else cnt = 0;\n }\n return ans%mod;\n }\n};\n```
1
0
['String', 'C++']
0
number-of-substrings-with-only-1s
Q1513 Accepted C++ ✅ Sliding Win & Counting | Easiest Method
q1513-accepted-c-sliding-win-counting-ea-4356
CRUX\n1) All single 1\'s are the part of the ans. Inital loop for counting the number of 1\'s in the string s.\n2) Keeping the count as 1 and increment if 1\'s
adityasrathore
NORMAL
2023-07-07T06:58:15.187206+00:00
2023-07-07T06:58:15.187240+00:00
347
false
CRUX\n1) All single 1\'s are the part of the ans. Inital loop for counting the number of 1\'s in the string s.\n2) Keeping the count as 1 and increment if 1\'s are found consecutively.\n3) Otherwise put count as 1 again.\n\nThe code is very readable, Please go through the code and read the above points again for better understanding .\n\n```\nclass Solution {\npublic:\n int MOD = 1e9 + 7;\n int numSub(string s) {\n int n = s.size();\n int ans = 0,count = 1;\n for(int i=0;i<n;i++)\n if(s[i] == \'1\')\n ans++;\n \n for(int i=1;i<n;i++){\n if(s[i] == \'1\' && s[i-1] == \'1\'){\n ans = (ans+count)%MOD;\n count++;\n }\n else\n count = 1;\n }\n return ans;\n }\n};\n```
1
0
['C', 'Sliding Window', 'Counting']
0
number-of-substrings-with-only-1s
[C++] || Easy to understand
c-easy-to-understand-by-riteshkhan-bgb5
\nclass Solution {\npublic:\n int numSub(string s) {\n long long c=0, p=0, t = pow(10,9);\n for(auto& i : s){\n if(i==\'1\'){\n
RiteshKhan
NORMAL
2022-12-16T08:02:39.853184+00:00
2022-12-16T08:02:39.853222+00:00
86
false
```\nclass Solution {\npublic:\n int numSub(string s) {\n long long c=0, p=0, t = pow(10,9);\n for(auto& i : s){\n if(i==\'1\'){\n ++c;\n }\n else{\n p += c*(c+1)/2;\n c=0;\n }\n }\n p += c*(c+1)/2;\n return p%(t+7);\n }\n};\n```
1
0
['C']
0
number-of-substrings-with-only-1s
Beginner Friendly|| Easy C++ Solution
beginner-friendly-easy-c-solution-by-pra-760a
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
Prashant-singh
NORMAL
2022-11-18T12:12:14.331364+00:00
2022-11-18T12:12:14.331404+00:00
836
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:\n int numSub(string s) {\n long long consecutiveOnes = 0, ans = 0, mod = 1e9+7;\n for(int i = 0; i < s.size(); i++){\n // if the string of consecutiveOnes get broken add the answer\n if(s[i] == \'0\'){\n ans += consecutiveOnes*(consecutiveOnes+1)/2;\n consecutiveOnes = 0; //Setting consecutiveOnes to 0 so that next time consecutiveOnes will be calculated from 0 not from a precalculated value\n }\n else consecutiveOnes++;\n }\n ans += consecutiveOnes*(consecutiveOnes+1)/2;\n return ans%mod;\n }\n};\n```
1
0
['C++']
1
number-of-substrings-with-only-1s
Most Optimal Java Solution
most-optimal-java-solution-by-prince077-2y54
\n public int numSub(String s) {\n long count = 0 , res = 0 , mod = (int)1e9+7 ;\n for(int i = 0 ; i < s.length() ; i++){\n count+=s.ch
prince077
NORMAL
2022-11-18T04:43:14.843926+00:00
2022-11-18T04:48:26.132716+00:00
906
false
```\n public int numSub(String s) {\n long count = 0 , res = 0 , mod = (int)1e9+7 ;\n for(int i = 0 ; i < s.length() ; i++){\n count+=s.charAt(i)-\'0\';\n if(s.charAt(i)-\'0\'==0){\n res+=((count*(count+1))/2);\n count = 0 ;\n }\n }\n res+=((count*(count+1))/2);\n return (int)(res%mod);\n }\n}\n```
1
0
[]
0
number-of-substrings-with-only-1s
c++ | easy to understand | short
c-easy-to-understand-short-by-venomhighs-0dor
\n# Code\n\nclass Solution {\npublic:\n int numSub(string s) {\n vector<long> dp(s.length(), 0);\n if(s[0] == \'1\')\n dp[0] = 1;\n
venomhighs7
NORMAL
2022-10-06T04:06:29.034239+00:00
2022-10-06T04:06:29.034286+00:00
679
false
\n# Code\n```\nclass Solution {\npublic:\n int numSub(string s) {\n vector<long> dp(s.length(), 0);\n if(s[0] == \'1\')\n dp[0] = 1;\n \n long sum = 0;\n for(int i = 1 ; i < s.length(); i++)\n {\n if(s[i] == \'1\')\n dp[i] = dp[i - 1] + 1;\n }\n for(int i = 0 ; i < dp.size() - 1; i++)\n {\n if(dp[i] != 0 and dp[i + 1] == 0)\n {\n sum += ((dp[i])*(dp[i] + 1)/2)% 1000000007;\n }\n }\n if(dp[dp.size() - 1] != 0)\n sum += ((dp[dp.size() - 1])*(dp[dp.size() - 1] + 1)/2)% 1000000007;\n return sum;\n }\n};\n```
1
0
['C++']
0
number-of-substrings-with-only-1s
Java Simple Solution | Runtime : 7ms
java-simple-solution-runtime-7ms-by-hars-6vuo
\nclass Solution {\n public int numSub(String s) {\n if(s.indexOf("1") < 0)\n return 0;\n int count = 0,res=0, mod = 1_000_000_007;\
Harsh_Kode
NORMAL
2022-09-06T16:08:17.803755+00:00
2022-09-06T16:08:17.803804+00:00
654
false
```\nclass Solution {\n public int numSub(String s) {\n if(s.indexOf("1") < 0)\n return 0;\n int count = 0,res=0, mod = 1_000_000_007;\n for(int i=0 ; i < s.length(); i++){\n count = s.charAt(i) == \'1\' ? count+1 : 0;\n res = (res + count) % mod;\n }\n return res;\n }\n}\n```
1
0
['Java']
1
number-of-substrings-with-only-1s
help needed!! sliding window logic.
help-needed-sliding-window-logic-by-deva-vjrz
54/56 testcases passed!!!\n\n\'\'\'\nclass Solution {\n public int numSub(String s) {\n int i,j;\n \n\t\ti=0;j=0;\n\t\tint ans=0;\n\t\twhile(j<s.le
devanshp
NORMAL
2022-08-15T17:12:14.929083+00:00
2022-08-15T17:12:14.929114+00:00
528
false
**54/56 testcases passed!!!**\n\n\'\'\'\nclass Solution {\n public int numSub(String s) {\n int i,j;\n \n\t\ti=0;j=0;\n\t\tint ans=0;\n\t\twhile(j<s.length())\n\t\t{\n\t\t if(s.charAt(j)==\'0\')\n\t\t {\n\t\t i=j+1;\n\t\t j++;\n\t\t }\n\t\t \n\t\t else if(s.charAt(j)==\'1\')\n\t\t {\n\t\t ans+=j-i+1;\n\t\t j++;\n\t\t }\n\t\t}\n\t\t\n return ans%1000000007;\n \n }\n}
1
0
['Sliding Window', 'Java']
1
number-of-substrings-with-only-1s
Run length counting C++ solution (O(n) and no branching)
run-length-counting-c-solution-on-and-no-dysy
We note that the number of sub-strings is just the partial sum of the natural numbers up until the length of the original string, i.e. given a string of 1\'s of
fpj
NORMAL
2022-07-26T09:33:42.087622+00:00
2022-07-26T09:33:42.087651+00:00
162
false
We note that the number of sub-strings is just the partial sum of the natural numbers up until the length of the original string, i.e. given a string of `1`\'s of length *N* we have *(N + (N + 1)) / 2* sub-strings.\n\nLet\'s look at a few examples.\n\n* For the input `1` we have 1 sub-string: `[1]`\n* For the input `11` we have 3 sub-strings: `[1, 1, 11]`\n* For the input `111` we have 6 sub-string: `[1, 1, 1, 11, 11, 111]`\n\nIn general, for the input `1...11` of length N we have:\n\n* *N* sub-strings of length *1*\n* *N-1* sub-strings of length *2*\n* *N-2* sub-strings of length *3*\n* ...\n* *2* sub-strings of length *N-1*\n* *1* sub-string of length *N*\n\nLooking carefully we see that the number of sub-strings are *1 + 2 + 3 + ... + N*. This is a well-known sum -- often referred to as "the partial sum of the natural numbers" or "the triangle numbers" [[1](https://en.wikipedia.org/wiki/1_%2B_2_%2B_3_%2B_4_%2B_%E2%8B%AF)].\n\nThe formula to compute the sum is *(N + (N + 1)) / 2*.\n\nNow that we can count the number of sub-strings *inside* a string of `1`\'s we just need a way to count how many there are in a row. This is quite easy.\n\nWe loop over the input string and as long as the current character is `1` we increment a *run length* counter. If we encounter a `0` (or the end of the input string) we just add the sub-strings using the formula above.\n\n```\nnumSub(S):\n sum := 0\n run := 0\n for i in 0...len(S)-1\n if S[i] == "1"\n \t run += 1\n \t else\n\t sum += (run + (run + 1)) / 2\n\t run = 0\n sum += (run + (run + 1)) / 2\n return sum % (1e9 + 7)\n```\n\nThere\'s a slight variant (maybe an optimization) that we can do here if we observe that the *run length* counter will be *1, 2, 3, ...* and if we want the sum of that added to the total why not just do that immediately?\n\n```\nnumSub(S):\n sum := 0\n run := 0\n for i in 0...len(S)-1\n if S[i] == "1"\n \t run += 1\n\t\t sum += run\n \t else\n\t run = 0\n return sum % (1e9 + 7)\n```\n\nAs a final optimization we can get rid of the branch altogether if we carefully update the *run length* counter depending on the current character in the input string. We need to do two things: 1) increment the counter if it\'s a `1` and 2) reset the counter if it\'s not a `1`.\n\n```\nnumSub(S):\n sum := 0\n run := 0\n for i in 0...len(S)-1\n run = run * (S[i] == "1") + (S[i] == "1")\n\t sum += run\n return sum % (1e9 + 7)\n```\n\nThis C++ solution uses 64-bit unsigned integers to avoid overflowing, but a more rigurous solution could do the modulo inside the loop.\n\n```\n int numSub(const string &s) {\n uint64_t count = 0;\n uint64_t run = 0;\n for (auto c : s) {\n run = run * (c == \'1\') + (c == \'1\');\n count += run;\n }\n return (int)(count % 1000000007);\n }\n```
1
0
['C', 'Iterator']
0
number-of-substrings-with-only-1s
C++ | Sliding Window || Commented Code || Diagram
c-sliding-window-commented-code-diagram-a3fw0
\n\n\nclass Solution {\npublic:\n int numSub(string s) {\n int i=0,j=0;\n int n = s.size();\n int res=0;\n for(;j<=n;j++){\n
p3jit
NORMAL
2022-07-20T08:11:51.190079+00:00
2022-07-20T17:44:17.486078+00:00
191
false
![image](https://assets.leetcode.com/users/images/0d71b179-e6f6-4131-889e-537be2134a46_1658304703.3028126.png)\n\n```\nclass Solution {\npublic:\n int numSub(string s) {\n int i=0,j=0;\n int n = s.size();\n int res=0;\n for(;j<=n;j++){\n if(s[j]==\'0\' or j==n){ // the moment our window breaks we will do our caclulation.\n long long len =j-i;\n if(len>0){\n long long sum = ((len*(len+1))%1000000007)/2; // as the contribution of the length is (n+1)*n/2;\n res += sum%1000000007;\n }\n i=j+1;// set lower bound of window to the next of break point.\n }\n }\n return res;\n }\n};\n\n// TC - O(N)\n// SC - O(1)\n```
1
0
['C', 'Sliding Window']
0
number-of-substrings-with-only-1s
java solution
java-solution-by-somidhroy-wsem
\nclass Solution {\n public int numSub(String s) {\n long count = 0;\n int n = 0;\n long mod = 1000000007;\n for(int i = 0; i < s
somidhroy
NORMAL
2022-06-20T04:36:16.814711+00:00
2022-06-20T04:50:38.223908+00:00
342
false
```\nclass Solution {\n public int numSub(String s) {\n long count = 0;\n int n = 0;\n long mod = 1000000007;\n for(int i = 0; i < s.length(); i++){\n if(s.charAt(i) == \'1\'){\n count = (count + ++n);\n }\n else{\n n = 0;\n }\n }\n return (int)(count % mod);\n }\n}\n```
1
0
['Java']
0
number-of-substrings-with-only-1s
C++ || EASY TO UNDERSTAND || Simple Solution
c-easy-to-understand-simple-solution-by-vmwpu
\n#define ll long long int\nll mod=1e9+7;\nclass Solution {\npublic:\n int numSub(string s) {\n int n=s.length();\n int c=1;\n ll ans=0;
aarindey
NORMAL
2022-06-12T00:17:32.040338+00:00
2022-06-12T00:17:32.040375+00:00
81
false
```\n#define ll long long int\nll mod=1e9+7;\nclass Solution {\npublic:\n int numSub(string s) {\n int n=s.length();\n int c=1;\n ll ans=0;\n int cnt=0;\n for(char ch:s)\n {\n cnt+=(ch-\'0\');\n }\n if(cnt==0)\n return 0;\n s+=\'0\';\n for(int i=1;i<n+1;i++)\n {\n if(s[i]==s[i-1]&&s[i]==\'1\')\n {\n c++;\n }\n else if(s[i]==\'0\'&&s[i-1]==\'1\')\n {\n ans+=c*(1ll)*(c+1)/2;\n ans=ans%mod;\n c=1;\n }\n \n }\n ans=ans%mod;\n return ans;\n }\n};\n```\n**Please upvote to motivate me in my quest of documenting all leetcode solutions(to help the community). HAPPY CODING:)\nAny suggestions and improvements are always welcome**
1
0
[]
0
number-of-substrings-with-only-1s
Number of Substrings With Only 1s | C++ Solution
number-of-substrings-with-only-1s-c-solu-kgf3
class Solution {\npublic:\n int numSub(string s) \n {\n int n=s.length();\n vectordp(n+1,0);\n for(int i=0;i<n;i++)\n {\n
prabhatm580
NORMAL
2022-03-08T05:32:23.797176+00:00
2022-03-08T05:32:23.797226+00:00
137
false
class Solution {\npublic:\n int numSub(string s) \n {\n int n=s.length();\n vector<int>dp(n+1,0);\n for(int i=0;i<n;i++)\n {\n if(s[i]==\'1\')\n dp[i+1]=dp[i]+1;\n }\n long long int res=0;\n for(int i=0;i<=n;i++)\n res=(res+dp[i])%1000000007;\n return res;\n }\n};
1
0
['Dynamic Programming', 'C', 'C++']
0
number-of-substrings-with-only-1s
Python easy to read and understand
python-easy-to-read-and-understand-by-sa-acgr
```\nclass Solution:\n def numSub(self, s: str) -> int:\n cnt, ans = 0, 0\n for i in range(len(s)):\n if s[i] == \'0\':\n
sanial2001
NORMAL
2022-03-02T19:24:11.309441+00:00
2022-03-02T19:24:11.309475+00:00
197
false
```\nclass Solution:\n def numSub(self, s: str) -> int:\n cnt, ans = 0, 0\n for i in range(len(s)):\n if s[i] == \'0\':\n cnt = 0\n else:\n cnt += 1\n ans += cnt\n return ans % ((10**9)+7)
1
0
['Python', 'Python3']
1
number-of-substrings-with-only-1s
C++ / O(n) time / Simple solution with explanation / count / no math formula
c-on-time-simple-solution-with-explanati-d6e9
Just use cnt to count # of consecutive 1 and add into res\n\nclass Solution {\npublic:\n int numSub(string s) {\n int n = s.size(), cnt = 0, res = 0,
pat333333
NORMAL
2022-02-20T06:02:14.236972+00:00
2022-02-20T06:03:45.808419+00:00
60
false
Just use `cnt` to count # of consecutive 1 and add into `res`\n```\nclass Solution {\npublic:\n int numSub(string s) {\n int n = s.size(), cnt = 0, res = 0, mod = 1e9+7;\n for (int i = 0; i < n; ++i) {\n cnt = s[i] == \'1\' ? cnt+1 : 0;\n res = (res+cnt) % mod;\n }\n return res;\n }\n};\n```
1
0
[]
0
number-of-substrings-with-only-1s
O(n) Time O(1) Space Java Solution
on-time-o1-space-java-solution-by-asamog-7741
Looking at strings of only 1s:\n1 should return 1, 11 should return 3, 111 should return 6, and so on.\nObserve that for a chain of k 1s, the expected result is
asamogh94
NORMAL
2021-11-28T06:56:49.014345+00:00
2021-11-28T06:57:48.856239+00:00
192
false
Looking at strings of only 1s:\n`1` should return 1, `11` should return 3, `111` should return 6, and so on.\nObserve that for a chain of `k` `1s`, the expected result is `k(k+1)/2`.\n\nKeep track of the length of the current chain of `1s` as you iterate through the string. Suppose the current chain of `1s` is of length `k` and you now see a `0`. Add `k(k+1)/2` to the result and reset the chain length count to `0`.\n\n```\nclass Solution {\n public int numSub(String s) {\n long val = 0;\n int result = 0;\n final int MOD = (int) (Math.pow(10, 9) + 7);\n for(int i = 0; i < s.length(); i++) {\n if(s.charAt(i) == \'0\') {\n val = val * (val + 1) / 2;\n result = (int) ((result + val) % MOD);\n val = 0;\n } else {\n val++;\n }\n }\n val = val * (val + 1) / 2;\n result = (int) ((result + val) % MOD);\n return result;\n }\n}\n```
1
0
['Java']
0
number-of-substrings-with-only-1s
O(n): Monotonic Stack
on-monotonic-stack-by-shaunakdas88-194i
For each possible index i of our string s, we can ask the simpler/local question of what is the number of substrings consisting exclusively of 1\'s that end at
shaunakdas88
NORMAL
2021-10-27T16:40:58.181811+00:00
2021-10-27T16:56:48.623584+00:00
78
false
For each possible index `i` of our string `s`, we can ask the simpler/local question of what is the number of substrings consisting exclusively of `1`\'s that end at index `i`. If we sum these local counts over all possible indices `i = 0, ..., n-1`, we will generate our desired answer.\n\nThere are two cases to consider, for each index `i`:\n\n* **character at `i` is `0`**: in this case, we know there are no substrings that end at index `i` consisting exclusively on `1`\'s, so we obtain a local count of 0 for this index\n* **character at `i` is `1`**: in this case, we need to determine the most recently encountered `0` in the string. Once we know such (should it exist), this will tell us how many substrings ending at `i` consist exclusively of `1`\'s.\n\n**MONOTONIC STACK**\nIn the second case above, the fact we want the most recent occurrence of something (in this case, a `0`) should immediately signal to us that we want to leverage a LIFO data structure. We can use a monotonic stack that is storing previously handled indexes. As we encounter a `1` at some index `i`, we keep popping indexes from the stack that correspond to prior occurrences of `1`\'s until we finally arrive at either:\n\n* an empty stack\n* the index `j` of the most recent `0`\n\nIn the first case, this means we only encountered `1`\'s up to this point, so every substring ending at index `i` (there are precisely `i+1` of them) will consist of only `1`\'s.\n\nIn the second case, there are precisely `i - j` substrings starting at index `j+1` and ending at index `i`.\n\n**CODE**\n```\nclass Solution:\n def numSub(self, s: str) -> int:\n s = [int(c) for c in s]\n n = len(s)\n \n count = 0\n stack = []\n for i in range(n):\n if s[i] == 1:\n while len(stack) > 0 and s[stack[-1]] != 0:\n stack.pop(-1)\n if len(stack) == 0:\n count += i + 1\n else:\n count += i - stack[-1]\n stack.append(i)\n \n return count % (10**9 + 7)\n```
1
0
[]
0
number-of-substrings-with-only-1s
C++ || EASY
c-easy-by-easy_coder-yign
```\nclass Solution {\npublic:\n int numSub(string s) {\n int ans=0;\n int i=0;\n int x=1e9+7;\n while(i<s.size()){\n
Easy_coder
NORMAL
2021-10-20T07:07:39.943215+00:00
2021-10-20T07:07:39.943249+00:00
96
false
```\nclass Solution {\npublic:\n int numSub(string s) {\n int ans=0;\n int i=0;\n int x=1e9+7;\n while(i<s.size()){\n if(i<s.size() && s[i]==\'1\'){\n int no_of_ones=0;\n while(i<s.size() && s[i]!=\'0\') {no_of_ones++; i++;}\n ans=(ans +(long long) no_of_ones * (no_of_ones+1) /2) % x; \n }\n else i++;\n }\n return ans;\n }\n};
1
0
[]
0
number-of-substrings-with-only-1s
C++ sol with comments
c-sol-with-comments-by-rakeshbodavula200-itf6
Idea--> find the length of the each substring which consists of 1\'s and let that length be n and\n\t\t\twe add n*(n+1)/2 to the sum which we return at last\n\n
rakeshbodavula2002
NORMAL
2021-10-04T06:02:19.308383+00:00
2021-10-04T06:02:19.308432+00:00
91
false
Idea--> find the length of the each substring which consists of 1\'s and let that length be n and\n\t\t\twe add n*(n+1)/2 to the sum which we return at last\n```\nint numSub(string s) {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n cout.tie(NULL);\n \n long long sum=0,count=0;\n int mod=7+pow(10,9);\n\t\t\n for(int i=0;i<s.length();i++){\n\t\t\n if(s[i]==\'1\') count++; // if s[i] is 1 then increase count\n\t\t\t\n else sum+=((count+1)*count/2)%mod,count=0;\n\t\t\t// if s[i] is 0 it means the 1\'s substring is broken so add that to the sum\n }\n sum+=((count+1)*count/2)%mod; // if the last character in the string is also 1\n\t\t//then we need to add that also\n\t\t\n return sum;\n }\n\t```
1
0
['C++']
0
number-of-substrings-with-only-1s
C# - Simple to understand
c-simple-to-understand-by-keperkjr-mc9n
\npublic class Solution {\n public int NumSub(string s) {\n var result = 0;\n var count = 0;\n var mod = (int)Math.Pow(10, 9) + 7;\n
keperkjr
NORMAL
2021-09-22T07:30:27.640296+00:00
2021-09-22T07:30:27.640333+00:00
53
false
```\npublic class Solution {\n public int NumSub(string s) {\n var result = 0;\n var count = 0;\n var mod = (int)Math.Pow(10, 9) + 7;\n \n foreach (var item in s) {\n if (item == \'1\') {\n ++count;\n } else {\n count = 0;\n } \n result = (result + count) % mod;\n }\n \n return result; \n }\n}\n```
1
0
[]
0
number-of-substrings-with-only-1s
C++
c-by-priyanka1230-kjk7
\n\npublic:\n int numSub(string s) {\n long long int i,f=0,sum=0;\n for(i=0;i<s.length();i++)\n {\n f=0;\n while(i
priyanka1230
NORMAL
2021-07-25T10:44:02.220667+00:00
2021-07-25T10:44:02.220697+00:00
79
false
```\n\n```public:\n int numSub(string s) {\n long long int i,f=0,sum=0;\n for(i=0;i<s.length();i++)\n {\n f=0;\n while(i<s.length()&&s[i]==\'1\')\n {\n f++;\n i++;\n }\n sum=sum+((f*(f+1))/2)%1000000007;\n }\n return sum;\n }\n};
1
0
[]
0
number-of-substrings-with-only-1s
Java easy trick
java-easy-trick-by-yash_patil-k5je
```\nclass Solution {\n public int numSub(String s) {\n int mod=(int)1e9+7;\n int count=0,res=0;\n for(int i=0;i<s.length();i++)\n
yash_patil
NORMAL
2021-07-12T11:58:22.535244+00:00
2021-07-12T11:58:22.535286+00:00
74
false
```\nclass Solution {\n public int numSub(String s) {\n int mod=(int)1e9+7;\n int count=0,res=0;\n for(int i=0;i<s.length();i++)\n {\n if(s.charAt(i)==\'1\')\n {\n count=(count+1)%mod;\n }\n else\n {\n count=0;\n }\n res=(res+count)%mod;\n }\n \n return res; \n }\n}
1
0
[]
0
number-of-substrings-with-only-1s
Python3 } One Pass | 30% |
python3-one-pass-30-by-idbasketball08-206v
\nclass Solution:\n def numSub(self, s: str) -> int:\n #strategy: One Pass\n left = right = -1\n answer, mod = 0, 10 ** 9 + 7\n f
idbasketball08
NORMAL
2021-06-17T20:56:49.330959+00:00
2021-06-17T20:56:49.330985+00:00
47
false
```\nclass Solution:\n def numSub(self, s: str) -> int:\n #strategy: One Pass\n left = right = -1\n answer, mod = 0, 10 ** 9 + 7\n for i in range(len(s)):\n #create new interval\n if s[i] == \'0\':\n left = right = i\n #update right side to keep our interval running\n else:\n right = i\n #find the size of the interval which corresponds to the # of substrings up to pos right\n answer = (answer + right - left) % mod\n return answer % mod\n \n```
1
0
[]
0
number-of-substrings-with-only-1s
Simple C++ O(N) Solution
simple-c-on-solution-by-ranjan_1997-bddq
\nclass Solution {\npublic:\n int numSub(string s) {\n int i = 0;\n int n = s.length();\n int result = 0;\n while(i<n)\n {
ranjan_1997
NORMAL
2021-05-30T11:48:58.780542+00:00
2021-05-30T11:48:58.780573+00:00
61
false
```\nclass Solution {\npublic:\n int numSub(string s) {\n int i = 0;\n int n = s.length();\n int result = 0;\n while(i<n)\n {\n int tot = 0;\n if(s[i] == \'1\')\n {\n while(s[i] == \'1\' and i<n)\n {\n tot++;\n result = (result+tot)%1000000007;\n i++;\n }\n }\n tot = 0;\n i++;\n }\n return result;\n }\n};\n```
1
0
[]
0
number-of-substrings-with-only-1s
C++ | O(n) 99.8% faster| with comments
c-on-998-faster-with-comments-by-shantan-zulx
\n#define MOD 1000000007\n\nclass Solution {\npublic:\n int numSub(string s) {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n lo
shantanu199
NORMAL
2021-05-26T22:06:25.862083+00:00
2021-05-26T22:06:25.862114+00:00
55
false
```\n#define MOD 1000000007\n\nclass Solution {\npublic:\n int numSub(string s) {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n long long int sum=0;\n int n=s.size();\n long long int count = s[0]==\'1\'? 1: 0;\n \n\t\t/*\n\t\tSubstring of 1s start: s[0]==\'1\' || s[i-1]==\'0\'&&s[i]==\'1\'\n\t\tSubstring of 1s end : s[n-1]==\'1\' || s[i-1]==\'1\'&&s[i]==\'0\'\n\t\tNumber of permutations of substring of 1s with size count = (count*(count+1))/2\n\t\t*/\n\t\t\n for (int i=1; i<n; i++){\n if (s[i]==\'1\'){\n if (s[i-1]==\'0\')\n count = 1;\n // s[i-1] == \'1\'\n else\n count++;\n }\n // s[i] == \'0\'\n else{\n if (s[i-1]= \'1\'){\n sum = (sum + (count*(count+1))/2)%MOD;\n count = 0;\n } \n }\n }\n sum = (sum + (count*(count+1))/2)%MOD;\n return sum%MOD;\n }\n};\n```
1
0
[]
0
number-of-substrings-with-only-1s
Simplest Java Solution One Pass, No Formula With Explanation
simplest-java-solution-one-pass-no-formu-0636
Intuition: The bruteforce way is to generate all the substrings and count all the substrings will all Ones. Time complexity for this would be :- O(n^3), which
amanthapliyal3
NORMAL
2021-05-15T15:49:58.055540+00:00
2021-05-15T15:49:58.055568+00:00
83
false
**Intuition:** The bruteforce way is to generate all the substrings and count all the substrings will all Ones. Time complexity for this would be :- O(n^3), which could be optimised to O(n^2) if we count while creating substrings.\n\nBut from here we can observe that at each index we only want to know all the substrings with one ending there. So, basically we only want the count of strings ending at current index with all ones.\nSo, now for each index we will have two options:- Either the character is \'1\' or \'0\'.\n\n**Case 1: When current character is one**\nAssuming our current index is \'i\' and count of substrings with all ones ending at \'i\' = count + 1( plus one for one at \'i\'). \n\n**Case : When current character is zero**\nSo, if our character at \'i\' is \'0\' then all the substrings ending at this index would contain zero. And so we cannot add this character to our substrings. And hence because substrings need to be contiguous we can say now we have zero substrings with all one and so we will change the count to 0.\n\nFor the final answer at each position we will add the count of substrings ending at the current position to the ans.\n\n**Time Complexity = O(n)\nSpace Complexity = O(1)**\n\n\n```\nclass Solution {\n public int numSub(String s) {\n int ans = 0;\n int ones = 0;\n int MOD = 1000000007;\n \n for(int i = 0; i < s.length(); i++) {\n if(s.charAt(i) == \'0\') ones = 0;\n else ones += 1;\n ans = (ans + ones) % MOD;\n }\n \n return ans;\n }\n}\n```
1
0
[]
0
number-of-substrings-with-only-1s
Java | Clean Solution
java-clean-solution-by-user8540kj-co06
This solution is not mine but i found this solution very interesting as it is beginner friendly\nSolution by : Nidhi_2125\nThe Idea is very simple you can count
user8540kj
NORMAL
2021-04-12T14:33:48.717056+00:00
2022-08-01T05:01:14.620790+00:00
153
false
**This solution is not mine but i found this solution very interesting as it is beginner friendly**\n*Solution by : Nidhi_2125*\n*The Idea is very simple you can count the number of ones and keep on checking the segment of one\'s (arr[i]==arr[i+1] ) if it is equal you can add this substring into your original substring count*\n```\nclass Solution {\n public int numSub(String s) {\n int count=0;\n \n char arr[]=s.toCharArray();\n int n=arr.length;\n for(int i=0;i<n;i++){\n if(arr[i]==\'1\') count++;\n }\n int substring=0;\n int mod=1000000007;\n for(int i=0;i<n-1;i++){\n if(arr[i]==\'1\' && arr[i]==arr[i+1]){\n substring++;\n }\n else{\n substring=0;\n }\n \n count=(count+substring)%mod;\n \n }\n return count;\n }\n}\n```
1
0
[]
1
number-of-substrings-with-only-1s
C++ Easy Solution beats 99%
c-easy-solution-beats-99-by-vibhu172000-6xpj
\nclass Solution {\npublic:\n int numSub(string s) {\n int cv= 1e9+7;\n long long count_ones=0;\n long long ans=0;\n for(int i=0;
vibhu172000
NORMAL
2021-03-30T13:00:38.440631+00:00
2021-03-30T13:00:38.440661+00:00
76
false
```\nclass Solution {\npublic:\n int numSub(string s) {\n int cv= 1e9+7;\n long long count_ones=0;\n long long ans=0;\n for(int i=0;i<s.size();i++)\n {\n if(s[i]==\'1\')\n {\n count_ones++;\n if(i+1==s.size() || s[i+1]!=\'1\')\n {\n long long vc=((count_ones)*(count_ones+1))/2;\n ans+=vc;\n count_ones=0;\n continue;\n }\n }\n }\n return (ans % cv);\n }\n};\n```
1
0
[]
0
number-of-substrings-with-only-1s
Easiest C++ Solution | 4 lines of code !
easiest-c-solution-4-lines-of-code-by-ra-w0sg
\nclass Solution {\npublic:\n int m=1000000007;\n int numSub(string s,long long ans=0,long long c=0) {\n for(int i=0; i<s.size(); i++) {\n
rac101ran
NORMAL
2021-03-19T00:31:21.475561+00:00
2021-03-19T00:31:21.475588+00:00
71
false
```\nclass Solution {\npublic:\n int m=1000000007;\n int numSub(string s,long long ans=0,long long c=0) {\n for(int i=0; i<s.size(); i++) {\n s[i]==\'0\'?ans+=((c*(c+1))/2)%m:c++; // add sum of length of substring in ans => (n*(n+1))/2\n c=s[i]==\'0\'?0:c; // if a 0 occurs just set the substring \'c\' var to 0 \n }\n ans+=((c*(c+1))/2)%m; // for the suffix,if \'0\' is not present the last substring is not calculated , ...111 in for loop\n return (int) ans;\n }\n};\n```
1
0
[]
0
number-of-substrings-with-only-1s
[C++]Really hate the extreme test samples
creally-hate-the-extreme-test-samples-by-ytia
with 1 \'1\' we got 1 substring\nwith 2 \'1\' we got 3 (2 + 1)\nwith 3 \'1\' we got 6 (3+ 2 + 1)\n...\nwith n \'1\' we got n*(n+1)/2\n\n int numSub(strin
wilbertgui
NORMAL
2021-02-20T09:35:16.536128+00:00
2021-02-20T09:36:56.344101+00:00
99
false
with 1 \'1\' we got 1 substring\nwith 2 \'1\' we got 3 (2 + 1)\nwith 3 \'1\' we got 6 (3+ 2 + 1)\n...\nwith n \'1\' we got n*(n+1)/2\n```\n int numSub(string s) {\n long cnt = 0; \n for(int i=0; i<s.size(); i++){\n long c1 = 0;\n while(s[i] == \'1\'){\n ++c1;\n ++i;\n }\n cnt += c1*(c1+1)/2; \n } \n return cnt%1000000007;\n }\n```
1
0
[]
1
number-of-substrings-with-only-1s
Python O(n) time, O(1) space, straight forward solution
python-on-time-o1-space-straight-forward-vzbp
\nclass Solution:\n def numSub(self, s: str) -> int:\n res=0\n count=0\n for ch in s:\n if ch == \'1\':\n coun
philipphil
NORMAL
2021-01-08T23:23:35.328284+00:00
2021-01-08T23:23:35.328316+00:00
76
false
```\nclass Solution:\n def numSub(self, s: str) -> int:\n res=0\n count=0\n for ch in s:\n if ch == \'1\':\n count+=1\n res+=count\n else:\n count=0\n \n return res % (10**9+7)\n```
1
0
[]
0
number-of-substrings-with-only-1s
Java easy solution
java-easy-solution-by-suryakant31-l886
class Solution {\n public int numSub(String s) {\n long count = 0;\n\n long result = 0;\n for(int i = 0; i< s.length() ; i++ ){\n\n
suryakant31
NORMAL
2021-01-02T16:20:00.992513+00:00
2021-01-02T16:20:00.992537+00:00
86
false
class Solution {\n public int numSub(String s) {\n long count = 0;\n\n long result = 0;\n for(int i = 0; i< s.length() ; i++ ){\n\n if(s.charAt(i) == \'1\'){\n count++;\n }\n\n if(s.charAt(i) == \'0\' || i == s.length()-1){\n result = result+find_num(count);\n count = 0;\n }\n\n\n\n\n }\n int result1 = (int)(result % ((int)Math.pow(10,9) + 7));\n return result1;\n }\n\n public long find_num( long n){\n if(n == 0){\n return 0;\n }\n long val = 0;\n for(int i=1; i<=n ;i++){\n val = val + i;\n }\n return val;\n }\n}
1
0
[]
0
number-of-substrings-with-only-1s
easy-peasy cpp solution
easy-peasy-cpp-solution-by-bitrish-28an
\nclass Solution {\npublic:\n int numSub(string s) {\n long ans = 0;\n for(int i=0;i<s.length();i++)\n { long c=0;\n while(
bitrish
NORMAL
2020-09-24T16:42:42.761820+00:00
2020-09-24T16:42:42.761862+00:00
138
false
```\nclass Solution {\npublic:\n int numSub(string s) {\n long ans = 0;\n for(int i=0;i<s.length();i++)\n { long c=0;\n while(s[i]==\'1\')\n {\n c++;\n i++;\n }\n ans += c*(c+1)/2;\n }\n return ans%1000000007;\n }\n};\n```
1
0
['Math', 'C', 'C++']
0
number-of-substrings-with-only-1s
Simple Java Solution
simple-java-solution-by-jyotiprakashrout-axhe
\nclass Solution {\n public int numSub(String s) {\n int count = 0;\n String [] ones = s.split("0");\n \n for(String one : ones){
jyotiprakashrout434
NORMAL
2020-08-06T21:50:34.597151+00:00
2020-08-06T21:50:34.597196+00:00
262
false
```\nclass Solution {\n public int numSub(String s) {\n int count = 0;\n String [] ones = s.split("0");\n \n for(String one : ones){\n int n = one.length();\n count += (n * (n + 1.0) / 2) % 1000_000_007;\n }\n return count; \n }\n}\n```
1
0
['Math', 'Java']
0
number-of-substrings-with-only-1s
[JS] | O(N) solution | simple math | With explanation
js-on-solution-simple-math-with-explanat-fuqi
111 possible substrings :- 1, 1, 1, 11, 11, 111\n\n\n\nFor consective n 1 the number of substrings possible is n * ( n + 1 ) / 2. Using this principal we can l
vivekjain202
NORMAL
2020-07-30T17:39:02.383704+00:00
2020-07-30T17:42:24.944236+00:00
89
false
`111` possible substrings :- `1, 1, 1, 11, 11, 111`\n\n\n\nFor consective n `1` the number of substrings possible is `n * ( n + 1 ) / 2`. Using this principal we can loop over the string and keep counting the consective one\'s once the current element is `0` we add it to `total += current * (current + 1) / 2` and reset `count = 0`. At the end of loop check if we have `current` greater than `0` add this to total ( this occurs when you have consective 1s at the end of string i.e. \'100111\' )\n\n```\nvar numSub = function(s) {\n let total = 0;\n let current = 0\n for(let char of s){\n if(char === \'0\'){\n total += current * (current + 1) / 2\n current = 0\n }else{\n current++\n }\n }\n if(current){\n total += current * (current + 1) / 2\n }\n return total % (Math.pow(10, 9) + 7)\n};\n```
1
1
[]
0
number-of-substrings-with-only-1s
CPP SIMPLE EASY SOLUTION
cpp-simple-easy-solution-by-chase_master-ctiq
\nclass Solution {\npublic:\n long long m=pow(10,9)+7;\n int numSub(string s) {\n long long i=0,j=0;\n int c=0;\n while(j<s.length()&
chase_master_kohli
NORMAL
2020-07-28T13:23:51.953203+00:00
2020-07-28T13:23:51.953253+00:00
93
false
```\nclass Solution {\npublic:\n long long m=pow(10,9)+7;\n int numSub(string s) {\n long long i=0,j=0;\n int c=0;\n while(j<s.length()&&i<s.length()){\n while(i<s.length()&&s[i]==\'0\')\n i++;\n j=i;\n while(j<s.length()&&s[j]==\'1\')\n j++;\n c+=((j-i)*(j-i+1))%m/2;\n c%=m;\n i=j;\n }\n return c;\n }\n};\n```
1
0
[]
0
number-of-substrings-with-only-1s
Easy counting (Python)
easy-counting-python-by-jinghuayao-ljcu
\nclass Solution:\n def numSub(self, s: str) -> int:\n res, MOD = 0, 10 ** 9 + 7\n for string in s.split(\'0\'):\n if string:\n
jinghuayao
NORMAL
2020-07-21T01:35:29.574011+00:00
2020-07-21T01:35:29.574057+00:00
64
false
```\nclass Solution:\n def numSub(self, s: str) -> int:\n res, MOD = 0, 10 ** 9 + 7\n for string in s.split(\'0\'):\n if string:\n num = len(string)\n res += (1 + num) * num // 2\n return res % MOD\n```
1
0
[]
0
number-of-substrings-with-only-1s
Python O(n) by sliding window [w/ Comment]
python-on-by-sliding-window-w-comment-by-fn3c
Python O(n) sol by sliding window\n\n---\n\nImplementation\n\n\nclass Solution:\n def numSub(self, s: str) -> int:\n \n # padding one dummy zer
brianchiang_tw
NORMAL
2020-07-18T07:30:22.631525+00:00
2021-05-09T03:25:27.507330+00:00
168
false
Python O(n) sol by sliding window\n\n---\n\n**Implementation**\n\n```\nclass Solution:\n def numSub(self, s: str) -> int:\n \n # padding one dummy zero as ending symbol\n s = s + \'0\'\n \n idx, first_1_idx, last_1_idx = 0, None, None\n prev = None\n size = len(s)\n \n counter = 0\n \n while idx < size:\n \n if s[idx] == \'1\':\n if first_1_idx is None:\n # head index of 1s\n first_1_idx = idx\n \n else:\n if prev == \'1\':\n # tail index of 1s\n last_1_idx = idx - 1\n \n # length of current contiguous 1s\n len_of_1 = last_1_idx - first_1_idx + 1\n \n # update count of substrings with 1s\n counter += len_of_1 * ( len_of_1 + 1 ) // 2 \n \n # clear index for new capture of 1s\n first_1_idx, last_1_idx = None, None\n \n prev = s[idx]\n idx = idx + 1\n \n return counter % (10**9 + 7)\n```\n\n---\n\nShare another solution with counter of contiguous 1s\n\n**Implementation**:\n\n```\nclass Solution:\n def numSub(self, s: str) -> int:\n \n\t\t# record of previous digit\n prev = 0\n \n number_of_substrings_of_1 = 0\n \n\t\t# linear scan\n for char in s:\n \n\t\t\t# type conversion to integer\n cur_num = int(char)\n \n if cur_num:\n\t\t\t\t# current digit is 1\n \n cur_num = prev + 1\n \n\t\t\t\t# add counter\n number_of_substrings_of_1 += cur_num\n \n prev = cur_num\n \n return number_of_substrings_of_1 % (10**9 + 7)\n \n```
1
0
['Sliding Window', 'Iterator', 'Python', 'Python3']
0
number-of-substrings-with-only-1s
Python3 44ms/14.7MB, beats 99/100%
python3-44ms147mb-beats-99100-by-dreamsm-14ez
The one-liner was slower.\n\n\nclass Solution:\n def numSub(self, s: str) -> int:\n vals = list(map(len, s.split("0"))) \n p = 0\n for i
dreamsmasher
NORMAL
2020-07-17T02:57:11.047670+00:00
2020-07-17T02:57:11.047700+00:00
53
false
The one-liner was slower.\n\n```\nclass Solution:\n def numSub(self, s: str) -> int:\n vals = list(map(len, s.split("0"))) \n p = 0\n for i in vals:\n p += (i * (i+1) // 2)\n return p % (1000000007) \n\t\t```
1
1
[]
1
number-of-substrings-with-only-1s
C# One-Liner
c-one-liner-by-mhorskaya-ra8o
\npublic int NumSub(string s) =>\n\t(int)(s.Split(\'0\')\n\t\t.Select(x => (long)x.Length * (x.Length + 1) / 2)\n\t\t.Sum() % (1_000_000_000 + 7));\n
mhorskaya
NORMAL
2020-07-16T06:30:51.522101+00:00
2020-07-16T06:31:22.234352+00:00
78
false
```\npublic int NumSub(string s) =>\n\t(int)(s.Split(\'0\')\n\t\t.Select(x => (long)x.Length * (x.Length + 1) / 2)\n\t\t.Sum() % (1_000_000_000 + 7));\n```
1
0
[]
0
number-of-substrings-with-only-1s
Python: faster / less memory than 100% (with explanation)
python-faster-less-memory-than-100-with-i7ltj
Solution:\nSplit the given string by the character \'0\'. \nYou get a list of strings, ie [\'\', \'1\', \'\', \'111\']\nAnd for each string, count the number of
catters
NORMAL
2020-07-15T00:26:39.913580+00:00
2020-07-15T00:26:39.913623+00:00
131
false
Solution:\nSplit the given string by the character \'0\'. \nYou get a list of strings, ie [\'\', \'1\', \'\', \'111\']\nAnd for each string, count the number of substrings it yields:\nFor the string \'\', there are 0 substrings.\nFor the string \'1\', there are 1 substrings, \'1\'.\nFor the string \'11\', there are 2 substrings, \'1\' and \'11\'.\nFor the string \'111\', there are 6 substrings, three \'1\'s, two \'11\'s, and one \'111\'.\n . . . generalize it ...\nFor a string of length n, there are n * (n + 1) / 2 substrings.\n\n```\nclass Solution:\n def numSub(self, s: str) -> int:\n # split into strings of ones only\n substrings = s.split(\'0\')\n \n # each substring of length n adds (n)*(n+1)/2 substrings\n # some strings will have length 0, and that\'s ok\n num = 0\n for sub in substrings:\n num += len(sub) * (len(sub) + 1) // 2\n return num % (10 ** 9 + 7)\n```\n\nDisclaimer: not sure about the 100% measurement (there is often some variation in runtime, I find) but it is definitely fast.
1
1
['Python', 'Python3']
1
number-of-substrings-with-only-1s
python, head-on, explained with some tips
python-head-on-explained-with-some-tips-2yjeo
\nclass Solution:\n def numSub(self, s: str) -> int:\n d,l = defaultdict(int),0\n for i,v in enumerate(s):\n if v==\'1\':\n
rmoskalenko
NORMAL
2020-07-13T20:35:55.783970+00:00
2020-07-13T20:40:23.445744+00:00
58
false
```\nclass Solution:\n def numSub(self, s: str) -> int:\n d,l = defaultdict(int),0\n for i,v in enumerate(s):\n if v==\'1\':\n l+=1\n else:\n d[l]+=1\n l=0\n d[l]+=1\n\n return sum( v*((k+1)*k//2) for k,v in d.items() ) % (10**9 + 7)\n```\n\nSo this is the most head-on approach. First, we count number of sequences of `1` for each length.\n\nThe dictionary `d` will look like: `length`:`number of occurencies`, `l` is the current lenght of `1`s. Basically if we see `1` - we increament `l` and when we see `0` - we updated our dictionary and reset the counter `l`.\n\n```\n for i,v in enumerate(s):\n if v==\'1\':\n l+=1\n else:\n d[l]+=1\n l=0\n```\n\nUsing `defaultdict(int)` makes our life easier because we don\'t need to worry about creating the first entry for a sequence of a particular lenght.\n\nThat `for` loop works great if we have a `0` after each seq of `1`s, but if `s` ends with a `1`, we need to add an extra line to handle that case:\n\n```\n d[l]+=1\n```\n\nOk, now we know the number of sequences and we know that each sequence of lenght `v` will contribute `(k+1)*k//2)` to the end result. We just need to take care of a couple things:\n\n1. `sum( v*((k+1)*k//2) for k,v in d.items() )` - the `v*` part simply says multiply by number of sequences.\n2. in Python the lenght of int is virtually unlimited, so we can apply ` % (10**9 + 7)` only ones to the final result. In other languages with limited int size, we might want to do it along the way.\n\nOne more thing. In this approach if we see something like `000` - we\'ll be incrementing d[0]. Technically this is not needed since those zero lenght sequences will be ignored in the end. So we can add and extra `if` to make sure that we only count non-zero sequences. However, running tests shows that that extra `if` would make it run slower, so it\'s not needed after all.\n\nThat\'s it!\n
1
0
[]
0
number-of-substrings-with-only-1s
C++ Sliding Window
c-sliding-window-by-oleksam-cp6g
\nint numSub(string s) {\n\tint res = 0;\n\tlong long curOnes = 0;\n\tint mod = 1000000007;\n\tfor (char c : s) {\n\t\tif (c == \'1\')\n\t\t\tcurOnes++;\n\t\tel
oleksam
NORMAL
2020-07-13T18:35:35.858211+00:00
2020-07-13T18:36:40.900232+00:00
147
false
```\nint numSub(string s) {\n\tint res = 0;\n\tlong long curOnes = 0;\n\tint mod = 1000000007;\n\tfor (char c : s) {\n\t\tif (c == \'1\')\n\t\t\tcurOnes++;\n\t\telse {\n\t\t\tres += (curOnes * (curOnes + 1) / 2) % mod;\n\t\t\tcurOnes = 0;\n\t\t}\n\t}\n\tif (curOnes)\n\t\tres += (curOnes * (curOnes + 1) / 2) % mod;\n\treturn res;\n}\n```\n
1
0
['C', 'Sliding Window', 'C++']
0
number-of-substrings-with-only-1s
C++ O(n) simple solution,40ms time
c-on-simple-solution40ms-time-by-rishabh-e9ax
\n int mod=1e9+7;\n int numSub(string s) {\n vector<long>ans;\n long count=0,sum=0;\n \n for(int i=0;i<s.length();i++)\n {
rishabhsp98
NORMAL
2020-07-13T06:26:14.336145+00:00
2020-07-13T06:26:14.336195+00:00
49
false
```\n int mod=1e9+7;\n int numSub(string s) {\n vector<long>ans;\n long count=0,sum=0;\n \n for(int i=0;i<s.length();i++)\n {\n char ch =s[i];\n count=0;\n if(ch==\'1\')\n {\n count++;\n i++;\n while(s[i] != \'0\' && i<s.length())\n {\n count++;\n i++;\n }\n ans.push_back(count);\n }\n }\n for(long &ele: ans)\n {\n sum+=(((ele + 1) * ele/2))%mod;\n }\n return sum%mod;\n }\n\n```
1
0
[]
0
number-of-substrings-with-only-1s
C++ with some math
c-with-some-math-by-shkvorets-fxbq
\nlong res=0, n=0, len=s.length();\n for(int i=0; i<len; i++){\n if(s[i]==\'1\'){ \n n++;\n if(i==len-1 || s[i+1
shkvorets
NORMAL
2020-07-13T04:16:06.213668+00:00
2020-07-13T04:17:30.070296+00:00
58
false
```\nlong res=0, n=0, len=s.length();\n for(int i=0; i<len; i++){\n if(s[i]==\'1\'){ \n n++;\n if(i==len-1 || s[i+1]==\'0\'){\n res+=n*(n+1)/2;\n n=0;\n }\n }\n }\n return res % 1000000007;\n```
1
0
[]
0
number-of-substrings-with-only-1s
[Python] Sliding window
python-sliding-window-by-locphan2207-szom
python\ndef numSub(self, s: str) -> int:\n start = 0\n result = 0\n for i in range(len(s)):\n if s[i] == "0": start=i+1\n
locphan2207
NORMAL
2020-07-12T19:29:15.797902+00:00
2020-07-12T19:29:15.797949+00:00
50
false
```python\ndef numSub(self, s: str) -> int:\n start = 0\n result = 0\n for i in range(len(s)):\n if s[i] == "0": start=i+1\n else: result += i-start+1 \n return result%(10**9+7)\n\n```
1
0
[]
0
maximum-building-height
[Python/C++] greedy solution with visual explanation - O(MlogM)
pythonc-greedy-solution-with-visual-expl-d702
Idea\n\nFirst of all, let\'s think about a simple scenario when there are only two restrictions. We can easily get the maximum height of the buildings between t
alanlzl
NORMAL
2021-04-25T04:01:37.352928+00:00
2021-04-25T04:32:12.591021+00:00
5,809
false
**Idea**\n\nFirst of all, let\'s think about a simple scenario when there are only two restrictions. We can easily get the maximum height of the buildings between these two restrictions. \n\nThe height is either bounded by two sides:\n\n<img src="https://assets.leetcode.com/users/images/836de0df-4fc7-41d5-9685-39564ec6666c_1619322826.3706574.png" height="120"/>\n\nor bounded by one side:\n<img src="https://assets.leetcode.com/users/images/a9b9ca2c-392f-4f96-afc5-ea6270376761_1619322886.655991.png" height="120"/>\n\nWe can calculate this maximum height in `O(1)` time.\n\nHowever, there can be lots of restrictions on both sides and sometimes the adjacent restrictions are not the tightest bound. We solve this issue by first "propagating" restrictions from left to right and then from right to right.\n\nFor example, ` n = 8, restrictions = [[2,1], [5,5], [7,1]]`:\n\n<img src="https://assets.leetcode.com/users/images/00b1bf58-8ab6-4586-9e38-6cef134bb1ea_1619323120.0084102.png" height="120"/>\n\nWe first propogate from left to right to tighten the restriction `[5,5]` to `[5,4]`:\n\n<img src="https://assets.leetcode.com/users/images/cfa9359a-4e2e-46e8-a059-45cc19426343_1619323163.4713392.png" height="120"/>\n\nThen right to left:\n\n<img src="https://assets.leetcode.com/users/images/5a35df60-deff-41c5-bc42-80a388844b3b_1619323204.9176645.png" height="120"/>\n\nNow, we calculate the maximum height between each adjacent restriction pairs to get the overall maximum height.\n\n<img src="https://assets.leetcode.com/users/images/d14c1218-29a3-43ab-8671-b9b1e7f47ba2_1619323249.6558657.png" height="120"/>\n\nPlease see code below for more details =)\n\n</br>\n\n**Complexity**\n\n- Time complexity: `O(NlogN)`\n- Space complexity: `O(1)` or `O(N)` if we copy the original array\n\n</br>\n\n**Python**\n```Python\nclass Solution:\n def maxBuilding(self, n: int, arr: List[List[int]]) -> int:\n arr.extend([[1, 0], [n, n - 1]])\n arr.sort()\n m = len(arr)\n \n for i in range(1, m):\n arr[i][1] = min(arr[i][1], arr[i-1][1] + arr[i][0] - arr[i-1][0])\n for i in range(m - 2, -1, -1):\n arr[i][1] = min(arr[i][1], arr[i+1][1] + arr[i+1][0] - arr[i][0])\n \n ans = 0\n for i in range(1, m):\n l, h1 = arr[i-1]\n r, h2 = arr[i]\n ans = max(ans, max(h1, h2) + (r - l - abs(h1 - h2)) // 2)\n return ans\n```\n\n\n**C++**\n```C++\nclass Solution {\npublic:\n int maxBuilding(int n, vector<vector<int>>& arr) {\n arr.push_back({1, 0});\n arr.push_back({n, n - 1});\n sort(arr.begin(), arr.end());\n int m = arr.size();\n \n for (int i = 1; i < m; ++i)\n arr[i][1] = min(arr[i][1], arr[i-1][1] + arr[i][0] - arr[i-1][0]);\n for (int i = m - 2; i >= 0; --i)\n arr[i][1] = min(arr[i][1], arr[i+1][1] + arr[i+1][0] - arr[i][0]);\n \n int ans = 0, l, h1, r, h2;\n for (int i = 1; i < m; ++i) {\n l = arr[i-1][0], r = arr[i][0], h1 = arr[i-1][1], h2 = arr[i][1];\n ans = max(ans, max(h1, h2) + (r - l - abs(h1 - h2)) / 2);\n }\n return ans;\n }\n};\n```\n\n\n\n
168
1
[]
22
maximum-building-height
C++ with picture, 2 passes
c-with-picture-2-passes-by-votrubac-dqpf
Intuition\nn could be quite large, but r.size() is limited to 100,000. So we should analyze restrictions, and compute the maximum height we can reach between ad
votrubac
NORMAL
2021-04-25T05:10:42.462535+00:00
2021-04-27T17:11:44.637047+00:00
4,251
false
#### Intuition\n`n` could be quite large, but `r.size()` is limited to 100,000. So we should analyze restrictions, and compute the maximum height we can reach between adjacent restrictions.\n\n#### Solution\nFirst, we sort our restrictions. Then, going from left to right, we compute the maximum possible height `h` between two restrictions `h1` and `h2`. For that, we just add the number of steps to `h1`. If `h` is higher than `h2`, we reduce it so it can descend to `h2`. If `h` is smaller than `h2`, we set `h2` to `h`.\n\nBasically, what we do is reduce each restriction to the maximum height we can possibly reach for that `id`, ignoring all restrictions afterwards. Now, we repeat the same going right-to-left, and the maximum `h` will be our result. Let us consdider this example:\n```\n10\n[[8,5],[9,0],[6,2],[4,0],[3,2],[10,0],[5,3],[7,3],[2,4]]\n```\n\nGoing left-to-right, we "shave" the height (blue) that cannot be possibly reached:\n![image](https://assets.leetcode.com/users/images/f1092e08-4f98-4833-9fe0-d4b51fc5185f_1619328195.645843.png)\n\nNow we go right-to-left, and "shave" the height (red) again:\n![image](https://assets.leetcode.com/users/images/e76b650b-e240-49b6-aca3-023c872987c5_1619543498.3504817.png)\n\n**C++**\nWe insert two sentinel restrictions for the start and the end of our building line. Also, we reverse the restrictions for the right-to-left pass, so that we can resuse the same `pass` function.\n\n```cpp\nint pass(vector<vector<int>>& r) {\n int res = 0;\n for (int i = 0; i < r.size() - 1; ++i) {\n auto h1 = r[i][1], h2 = r[i + 1][1];\n auto h = h1 + abs(r[i + 1][0] - r[i][0]);\n if (h > h2)\n h = h2 + (h - h2) / 2;\n res = max(res, h);\n r[i + 1][1] = min(h, h2);\n }\n return res;\n}\nint maxBuilding(int n, vector<vector<int>>& r) {\n r.insert(r.end(), {{1, 0}, {n, n - 1}});\n sort(begin(r), end(r));\n pass(r);\n reverse(begin(r), end(r));\n return pass(r);\n}\n```\n**Complexity Analysis**\n- Time: O(r log r), where r is the number of restrictions.\n- Memory: O(1) or O(r) if we cannot modify the input vector.
71
2
[]
11
maximum-building-height
Java solution with easy to understand explanation
java-solution-with-easy-to-understand-ex-u6wz
The height of building i will depend on maximum 3 factors:\n1. The restriction on i th building (if there is any)\n2. The height of left building.\n3. The heigh
divyagarg2601
NORMAL
2021-04-30T04:55:55.838482+00:00
2021-04-30T04:57:17.609234+00:00
1,303
false
The height of building `i` will depend on maximum 3 factors:\n1. The restriction on `i th` building (if there is any)\n2. The height of left building.\n3. The height of right building.\n\nLet\'s understand it with the help of example.\nSuppose we have restrictions as: `[ [ 2, 1 ], [ 5, 6 ], [ 7, 1 ] ]`\n![image](https://assets.leetcode.com/users/images/17d5868b-8222-4b28-83a0-986b29d02d76_1619757442.2046905.png)\n\nThe height of building at index 5 will depend on restriction on index 2 as well as restriction on index 7.\nTo calculate maximum height of building at an index, we will have to run 2 loops:\n1. From left to right: to calculate maximum height at an index due to left building.\n2. From right to left: to calculate maximum height at an index due to right building.\n\nIn our example. building at index 5 will be reduced to 4 due to left buildings:\n![image](https://assets.leetcode.com/users/images/88695447-452e-4125-99c6-9da5ffeea967_1619757930.07478.png)\n\nand it will be further reduced to 3 due to right buildings:\n![image](https://assets.leetcode.com/users/images/6c490d9b-4b45-48a9-ac4a-611bcebfed35_1619758046.7682934.png)\n\nAfter calculating maximum height of buildings with restrictions, we can easily find maximum height between two buildings:\n\n```\nclass Solution {\n public int maxBuilding(int n, int[][] restrictions) {\n // sorting restrictions according to index.\n Arrays.sort(restrictions, (a, b) -> a[0] - b[0]);\n int len = restrictions.length + 2;\n int[][] arr = new int[len][2];\n arr[0][0] = 1;\n arr[0][1] = 0;\n arr[len-1][0] = n;\n arr[len-1][1] = n-1;\n for(int i = 1; i<len-1; ++i){\n arr[i] = restrictions[i-1];\n }\n \n // looping from left to right\n for(int i = 0; i<len-1; ++i){\n arr[i+1][1] = Math.min(arr[i+1][1], arr[i][1] + (arr[i+1][0] - arr[i][0]));\n }\n \n // looping from right to left\n for(int i = len-1; i>0; --i){\n arr[i-1][1] = Math.min(arr[i-1][1], arr[i][1] + (arr[i][0] - arr[i-1][0]));\n }\n \n int max = 0;\n \n for(int i = 0; i<len-1; ++i){\n int j = arr[i][0], h1 = arr[i][1], k = arr[i+1][0], h2 = arr[i+1][1];\n \n // calculating difference between heights of both buildings.\n int diff = Math.max(h1, h2) - Math.min(h1, h2);\n j += diff;\n \n // calculating maximum height possible between both buildings.\n max = Math.max(max, Math.max(h1, h2) + (k - j)/2);\n }\n \n return max;\n }\n}\n```\n\n**Note - please upvote if you like the explanation. If you have any doubts, please ask in the comment section, I\'ll be happy to answer : )**\n\n\n
22
0
[]
0
maximum-building-height
Python O(N) with explanation - 3 pass or 2 pass
python-on-with-explanation-3-pass-or-2-p-bgia
sort restriction (A) by first, then if A does not start from [1, 0], add or change the first element in A to [1, 0]\nThen go from left to right, check the pair
kai-leetcode
NORMAL
2021-04-25T04:44:45.661143+00:00
2021-04-25T18:06:22.311056+00:00
1,048
false
sort restriction (A) by first, then if A does not start from [1, 0], add or change the first element in A to [1, 0]\nThen go from left to right, check the pair of A[i], A[i+1] to see if A[i+1][1] is achievable. If not, update A[i+1][1] to the maximum achievable number by the rule. That\'s my first loop.\n\nThen go from right to left, check the pair of A[i], A[i-1] to see if A[i-1][1] is achievable. That\'s the second loop.\n\nInitial the result (res) as the maximum value at position n using A[-1].\n\nNow, you can guarantee that the every element in restriction is achievable by the rule and find the maximum height within each pair of A[i] and A[i+1]. Suppose that maximum point happens at position x with height y (x, y may be float here), we have the math equations\nx - A[i][0] = y - A[i][1]\nA[i+1][0] - x = y - A[i+1][1]\nsolve out y = (A[i+1][0] - A[i][0] + A[i][1] + A[i+1][1]) // 2 (need to round down to integer),\nwhich is the third loop.\n\n```\nclass Solution:\n def maxBuilding(self, n: int, A: List[List[int]]) -> int:\n A.sort()\n if not A or A[0][0] != 1:\n A = [[1, 0]] + A\n N = len(A)\n for i in range(N - 1):\n if abs(A[i][1] - A[i+1][1]) > abs(A[i][0] - A[i+1][0]):\n A[i+1][1] = min(A[i+1][1], A[i][1] + A[i+1][0] - A[i][0])\n for i in range(N - 1, 0, -1):\n if abs(A[i][1] - A[i-1][1]) > abs(A[i][0] - A[i-1][0]):\n A[i-1][1] = min(A[i-1][1], A[i][1] + A[i][0] - A[i-1][0])\n res = n - A[-1][0] + A[-1][1]\n for i in range(N - 1):\n res = max(res, (A[i+1][0] - A[i][0] + A[i][1] + A[i+1][1]) // 2)\n return res\n```\n\nIf you would like a simplied 2 pass solution. Here is the one:\n```\nclass Solution:\n def maxBuilding(self, n: int, A: List[List[int]]) -> int:\n A.sort()\n if not A or A[0][0] != 1:\n A = [[1, 0]] + A\n elif A[0][0] == 1:\n A[0][1] = 0 \n N = len(A)\n for i in range(N - 1):\n A[i+1][1] = min(A[i+1][1], A[i][1] + A[i+1][0] - A[i][0])\n res = n - A[-1][0] + A[-1][1]\n for i in range(N - 1, 0, -1):\n A[i-1][1] = min(A[i-1][1], A[i][1] + A[i][0] - A[i-1][0])\n res = max(res, (A[i][0] - A[i-1][0] + A[i-1][1] + A[i][1]) // 2)\n return res\n```
12
1
[]
6