Given an array of passwords and an integer k, accept passwords until they have been accepted k times
ex. [”abc”, “abc”, “abc”] k=2 → [accepted, accepted, rejected]
this code counts the occurrence of each password and accepts/rejects based on that but fails to accept the first k occurrences of each password
def fun(passwords, k):
freq = {}
if p not in passwords:
freq[p] = 1
else:
freq[p] += 1
arr = []
for p in passwords:
if freq[p] >= k:
arr.append("REJECT")
else:
arr.append("ACCEPT")
return arr
arr = ["str1", "str1", "str1"]
k = 2
fun(arr, k) -> ["REJECT", "REJECT", "REJECT"]
# should be
fun(arr, k) -> ["ACCEPT", "ACCEPT", "REJECT"]
this code keeps a running counter per password as it iterates through the list
i.e. if the count for the current password hasn’t hit k yet then accept
def fun(passwords, k):
counts = {}
result = []
for p in passwords:
# get the stored freq of p if it already exists or 0 if DNE, add 1
curr = counts.get(p, 0) + 1
# update freq
counts[p] = curr
if curr <= k:
result.append("ACCEPT")
else:
result.append("REJECT")
return result
Given an array of integers, find the total number of ways it can be split so that the left subarray sum is larger than the right
def fun(arr):
total = sum(arr) # sum of all elements in arr
left = 0
count = 0
# test splitting after each index
for i in range(len(arr)-1):
left += arr[i]
right = total - left
if left > right:
count += 1
return count
arr = [2, 1, -1, 4, 0]
fun(arr) -> 2