Digit-String Half Anagram
Frequency: Reported
Given a string containing only digits, modify its first half so that it becomes an anagram of the second half. In one operation, replace any digit with any other digit from 0 through 9. Return the minimum number of operations.
Example
text
s = "123212"The halves are "123" and "212". Replace the 3 in the first half with 2, producing "122", which is an anagram of the second half. Return 1.
Function
text
getAnagram(string s) -> intConstraints
text
1 < n < 10^5
s contains digits only
len(s) is a multiple of 2Submitted implementation
python
def getAnagram(s):
n = len(s)
half = n // 2
first_half = s[:half]
second_half = s[half:]
count_first = [0] * 10
count_second = [0] * 10
for digit in first_half:
count_first[int(digit)] += 1
for digit in second_half:
count_second[int(digit)] += 1
operations = 0
for i in range(10):
if count_first[i] > count_second[i]:
operations += count_first[i] - count_second[i]
return operations