https://www.acmicpc.net/problem/10816
v easy q with hashmap. But it can be solved with binary search. how??
import sys
from collections import defaultdict
input = sys.stdin.readline
n=int(input())
lst=list(map(int,input().split()))
m=int(input())
hola=list(map(int,input().split()))
ans=defaultdict(int)
real_ans=[]
for i in lst:
ans[i]+=1
for i in hola:
real_ans.append(ans[i])
print(*real_ans)
With binary search, we search for the left and right index where our target number is. Then, subtracting right with minus gives us the frequency of that target number in our list. The key is the bisect_left function, which has time complexity of log N.
import sys
from bisect import bisect_left, bisect_right
input = sys.stdin.readline
n = int(input()) # Read the number of cards Sanggeun has
lst = list(map(int, input().split())) # List of cards Sanggeun has
m = int(input()) # Number of queries
hola = list(map(int, input().split())) # The target numbers to check
# Sort the list of cards for binary search
lst.sort()
# Function to find the count of a target in the sorted list
def count_occurrences(lst, target):
left = bisect_left(lst, target) # Find first occurrence
right = bisect_right(lst, target) # Find one past the last occurrence
return right - left # The count is the difference between the two indices
# For each query, find the count of that target in lst
real_ans = [count_occurrences(lst, target) for target in hola]
# Print the results as space-separated integers
print(*real_ans)
Sorting the List:
N has a time complexity of O(N log N).Handling Each Query:
bisect_left(lst, target) performs a binary search to find the index of the first occurrence of the target. It runs in O(log N) time.bisect_right(lst, target) performs a binary search to find the index of one past the last occurrence of the target. It also runs in O(log N) time.Final Complexity:
N takes O(N log N).M queries, the total time complexity for handling all queries is O(M log N).Therefore, the overall time complexity is:
Thus, the final total time complexity is:
Space for the Sorted List:
lst stores N elements. Sorting it in place requires O(N) additional space.Space for Storing Results:
M, so the space for the result is O(M).Binary Search Operations:
bisect_left and bisect_right) operates in O(1) extra space, as they work directly on the list.Thus, the overall space complexity is:
This approach is efficient and scales well for large input sizes.