You can use the two-pointer technique, we can keep two pointers - p1 in the first list and p2 in the second list. We keep on incrementing p1 till the number at p1 in list1 is smaller than the number at p2 in list2. Otherwise, just increment the count by number of elements we have to the right of p1
def smaller_count(list1, list2):
l1, l2, ans = len(list1), len(list2), 0
# pointers in list1 and list2
p1, p2 = 0, 0
while p1 < l1 and p2 < l2:
if list1[p1] > list2[p2]:
ans += l1 - p1
p2 += 1
else:
p1 += 1
return ans
>>> smaller_count([1,4,6,8], [4,6,7,9])
4
>>> smaller_count([1,4,6,8], [0])
4
>>> smaller_count([1,4,6,8], [10])
0
>>> smaller_count([1,4,6,8], [0, 1, 2, 3])
13
Since we are iterating over the two lists only once, the complexity would be O(len(list1) + len(list2))