A. Love Story
Given that the length of the provided string is 10, the approach involves iterating through the string and comparing each character at position i with the corresponding character at position i in "codeforces."
t = int(input())
c = "codeforces"
for _ in range(t):
s = input()
res = 0
for i in range(10):
if s[i] != c[i]:
res += 1
print(res)
B. Short Substrings
Consider the first character in each pair.
Take every other character starting from the first one. Since the last character can not be a starting letter for a pair, add it to 'a' last.
t = int(input())
for _ in range(t):
b = input()
a = [] # Storing the characters in a list and appending gives a better time complexity compared to string concatenation
for index in range(0, len(b), 2):
a.append(b[index])
a.append(b[-1])
a = "".join(a)
print(a)
C. Yet Another Palindrome Problem
Any palindrome subsequence with length ≥ 3 also contains a palindrome with length = 3 as its subsequence.
The first observation is that we can always try to find the palindrome of length 3 (otherwise, we can remove some numbers from the middle until its length becomes 3).
The second observation is that the palindrome of length 3 is two equal numbers and some other (maybe, the same) number between them. For each number we only need to consider its left and right occurrences (if there is any number between them).
t = int(input())
for _ in range(t):
N = int(input())
nums = list(map(int, input().split()))
left_occurrence = {}
found = False
for i, n in enumerate(nums):
if n in left_occurrence:
if i - left_occurrence[n] >= 2:
found = True
break
else:
left_occurrence[n] = i
if found:
print("YES")
else:
print("NO")
D. Same Differences
Can you rewrite the formula?
The equation $$$a_j - a_i = j - i$$$ can be transformed into $$$a_j - j = a_i - i$$$, and let $$$b_i = a_i - i$$$. Then we need to count the number of pairs $$$(i, j)$$$ where $$$b_i = b_j$$$. We can use a dictionary(hash map) to count occurrences of each difference $$$(b_i)$$$.
T = int(input())
for _ in range(T):
N = int(input())
a = list(map(int,input().split()))
difference_count = {}
pair_count = 0
for i in range(N):
difference = a[i] - i
pair_count += difference_count.get(difference, 0)
difference_count[difference] = difference_count.get(difference, 0) + 1
print(pair_count)