ANCO

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 66 and the value at the second index is 77.

Solution for Subcases 1 and 2 (N≤103N \leq 10^3)

Given that NN is at most 10310^3, an O(N2)O(N^2) solution would suffice here. For every index in the string, we can perform the following algorithm:
  • If the value at that index is a 66, we loop through the rest of the string and add 11 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 O(N)O(N) solution, and there is a way. The key insight to this problem is not at the 66’s, but rather at the 77’s. We note that at every instance of 77 in our string, a six-seven can be made from every single 66 before that 77.
Thus, the problem can be solved through one complete search of the string s, making the solution O(N)O(N).
  • We can utilize a counter that counts the number of 66’s we have seen so far.
  • We can use a dictionary/HashMap to keep track of how many 66’s we have seen so far at every index.
  • We can use a list that stores all the indices that have 77’s.
The complete solution is as follows:
  1. Loop through every index of the string exactly once.
  2. If the index’s value is 66, add 11 to our number of 66’s we have seen so far, and then record the number of 66’s we have seen so far at the current index in our dictionary/HashMap.
  3. Otherwise, the index’s value must be 77, 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 66’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 NN elements in this list, and this loop is not nested in any other loop, so the time complexity would remain O(N)O(N).)

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 O(N)O(N) solution without using any lists/arrays/ArrayLists and dictionaries/HashMaps.
← Back to problem