# A. Remove Digit From Number to Maximize Result (opens new window)
Brute Force, for each digit in number
that equals digit
, remove it and compare the rest string. Find out the largest such string.
DETAILS
def removeDigit(self, N: str, d: str) -> str:
res = []
N = list(N)
for i, n in enumerate(N):
if n == d:
tmp = N[:i] + N[i + 1:]
res.append(tmp)
a = sorted(res)[-1]
return "".join(a)
# B. Minimum Consecutive Cards to Pick Up (opens new window)
Iterate over cards
and dynamically update the position of the last occurence of each card. If the current cards[i] = card
has the previous position of j
(cards[j] = card[i] = card
), then number of consecutive cards we have to collect is j - i + 1
.
DETAILS
def minimumCardPickup(self, cards: List[int]) -> int:
res, pos = 10 ** 6, collections.defaultdict(int)
for i, card in enumerate(cards):
if card not in pos:
pos[card] = i
else:
res = min(res, i - pos[card] + 1)
pos[card] = i
return res if res < 10 ** 6 else -1
# C. K Divisible Elements Subarrays (opens new window)
Save every unique list in a hashtable.
DETAILS
def countDistinct(self, nums: List[int], k: int, p: int) -> int:
n, res, pos = len(nums), set(), []
for i, num in enumerate(nums):
if num % p == 0:
pos.append(i)
pre = 0
for i, num in enumerate(nums):
if pre + k >= len(pos):
end = n
else:
end = pos[pre + k]
for j in range(i, end):
res.add(tuple(nums[i:j + 1]))
if num % p == 0:
pre += 1
return len(res)
# D. Total Appeal of A String (opens new window)
Prefix sum.
For each character ch
, we calculate the total appeal of all the substrings that end by ch. For example, given s = abcde
, all the substrings end by c
are abc, bc, c
.
We need to save the last occurrence of each unique character in prefix string end by ch
. For example, given s = aabbcdd
, for ch = c
. We have {a
= 1, b
= 3, c
= 4}.
Next step is to calculate the total appeal of this group of substrings. Notice that the number of unique characters ONLY change at those "last occurrence" indexes {1, 3, 4}
.
DETAILS
def appealSum(self, s: str) -> int:
res, n, d = 1, len(s), collections.defaultdict(int)
d[s[0]] = 0
for i in range(1, n):
d[s[i]] = i
tmp = sorted(list(d.values()))
pre, ss = -1, 0
for i, a in enumerate(tmp):
ss + =(len(tmp) - i) * (a - pre)
pre = a
res += ss
return res