I recently solved problem CSUB from the ‘Easy’ category.
The problem is:
Given a string S consisting of only 1s and 0s , find the number of substrings which start and end both in 1 .
In this problem, a substring is defined as a sequence of continuous characters Si, Si+1, …, Sj where 1 ≤ i ≤ j ≤ N .
When I submitted my solution as this code:
testcases = int(input()) # number of testcases
for o in range(testcases):
n = int(input()) # length of string, useless for this logic
sstr = input() # given string
no1 = 0 # number of '1's in string
for x in range(len(sstr)): # \
if sstr[x] == "1": # | - finding number of 1's in string
no1 += 1 # /
print(int(no1*(no1-1)/2 + no1))
it required 0.06 sec to be executed.
But when this code was submitted:
testcases = int(input()) # number of testcases
for o in range(testcases):
n = int(input()) # length of string, useless for this logic
sstr = int(input()) # given string
no1 = 0 # number of '1's in string
for x in str(sstr):
if x == "1":
no1 = no1 + 1
print(int(no1*(no1-1)/2 + no1))
it required 0.20 sec to be executed!!
Why is there so much of a difference?