<p>You are given two integer arrays <code>nums1</code> and <code>nums2</code> both of the same length. The <strong>advantage</strong> of <code>nums1</code> with respect to <code>nums2</code> is the number of indices <code>i</code> for which <code>nums1[i] &gt; nums2[i]</code>.</p>

<p>Return <em>any permutation of </em><code>nums1</code><em> that maximizes its <strong>advantage</strong> with respect to </em><code>nums2</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> nums1 = [2,7,11,15], nums2 = [1,10,4,11]
<strong>Output:</strong> [2,11,7,15]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> nums1 = [12,24,8,32], nums2 = [13,25,32,11]
<strong>Output:</strong> [24,32,8,12]
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums1.length &lt;= 10<sup>5</sup></code></li>
	<li><code>nums2.length == nums1.length</code></li>
	<li><code>0 &lt;= nums1[i], nums2[i] &lt;= 10<sup>9</sup></code></li>
</ul>

from typing import List
from collections import Counter

class Solution:
    def advantageCount(self, nums1: List[int], nums2: List[int]) -> List[int]:
        def binary_search(search_vals, *, is_good: "func", finding_min: "bool"):
            left_i = 0
            right_i = len(search_vals) - 1
            while left_i <= right_i:
                mid_i = left_i + (right_i - left_i) // 2
                is_valid = is_good(mid_i)
                if is_valid == finding_min:
                    right_i = mid_i - 1
                else:
                    left_i = mid_i + 1
            
            final_i = left_i if finding_min else left_i - 1
            return final_i if 0 <= final_i < len(search_vals) and is_good(final_i) else -1
        
        nums1.sort()
        nums1_dict = Counter(nums1)
        nums1_keys = sorted(nums1_dict.keys())
        answers = []

        for num2 in nums2:
            nums1_i = binary_search(
                nums1_keys,
                finding_min=True,
                is_good=lambda i: nums1_keys[i] > num2 and nums1_dict[nums1_keys[i]] > 0
            )
            
            if nums1_i == -1:
                i = binary_search(
                    nums1_keys,
                    finding_min=True,
                    is_good=lambda i: nums1_dict[nums1_keys[i]] > 0
                )
                assert i != -1
                answers.append(nums1_keys[i])
                nums1_dict[nums1_keys[i]] -= 1
                if nums1_dict[nums1_keys[i]] == 0:
                    nums1_keys.pop(i)
            else:
                answers.append(nums1_keys[nums1_i])
                nums1_dict[nums1_keys[nums1_i]] -= 1
                if nums1_dict[nums1_keys[nums1_i]] == 0:
                    nums1_keys.pop(nums1_i)

        return answers

38852