Stephan Says Six Seven — Solution
Recall that a six-seven is essentially a pair of two indices, the first one before the second, such that the value at the first index is and the value at the second index is .
Solution for Subcases 1 and 2 ()
Given that is at most , an solution would suffice here. For every index in the string, we can perform the following algorithm:
- If the value at that index is a , we loop through the rest of the string and add to our count of six-sevens.
- Otherwise, we don’t do anything.
Python solution for these 2 subcases
def solve(n, s):
count = 0
for i in range(n):
if s[i] == '6':
for j in range(i+1, n):
if s[j] == '7':
count += 1
return count
n = int(input())
s = str(input())
print(solve(n, s))Full credit solution
We seek an solution, and there is a way. The key insight to this problem is not at the ’s, but rather at the ’s. We note that at every instance of in our string, a six-seven can be made from every single before that .
Thus, the problem can be solved through one complete search of the string s, making the solution .
- We can utilize a counter that counts the number of ’s we have seen so far.
- We can use a dictionary/HashMap to keep track of how many ’s we have seen so far at every index.
- We can use a list that stores all the indices that have ’s.
The complete solution is as follows:
- Loop through every index of the string exactly once.
- If the index’s value is , add to our number of ’s we have seen so far, and then record the number of ’s we have seen so far at the current index in our dictionary/HashMap.
- Otherwise, the index’s value must be , so we add the index to our list of 7s’ indices.
Then, loop through every index in our 7s’ indices list and add the number of ’s before that index (we get this value from our dictionary/HashMap) to our answer. (This is a safe operation because there would be at most elements in this list, and this loop is not nested in any other loop, so the time complexity would remain .)
Python solution
n = int(input())
s = str(input())
count_sixes = {}
ind_sevens = []
num_sixes = 0
ans = 0
for i in range(n):
if s[i] == '6':
num_sixes += 1
else:
ind_sevens.append(i)
count_sixes[i] = num_sixes
for i in range(len(ind_sevens)):
ans += count_sixes[ind_sevens[i]]
print(ans)BONUS: Find an solution without using any lists/arrays/ArrayLists and dictionaries/HashMaps.