- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 60 lines of Java from the credited upstream file 2040.java.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public long kthSmallestProduct(int[] nums1, int[] nums2, long k) {3 List<Integer> A1 = new ArrayList<>();4 List<Integer> A2 = new ArrayList<>();5 List<Integer> B1 = new ArrayList<>();6 List<Integer> B2 = new ArrayList<>();7 8 seperate(nums1, A1, A2);9 seperate(nums2, B1, B2);10 11 final long negCount = A1.size() * B2.size() + A2.size() * B1.size();12 int sign = 1;13 14 if (k > negCount) {15 k -= negCount; 16 } else {17 k = negCount - k + 1; 18 sign = -1;19 List<Integer> temp = B1;20 B1 = B2;21 B2 = temp;22 }23 24 long l = 0;25 long r = (long) 1e10;26 27 while (l < r) {28 final long m = (l + r) / 2;29 if (numProductNoGreaterThan(A1, B1, m) + numProductNoGreaterThan(A2, B2, m) >= k)30 r = m;31 else32 l = m + 1;33 }34 35 return sign * l;36 }37 38 private void seperate(int[] arr, List<Integer> A1, List<Integer> A2) {39 for (final int a : arr)40 if (a < 0)41 A1.add(-a);42 else43 A2.add(a);44 Collections.reverse(A1); 45 }46 47 private long numProductNoGreaterThan(List<Integer> A, List<Integer> B, long m) {48 long count = 0;49 int j = B.size() - 1;50 51 52 for (final long a : A) {53 while (j >= 0 && a * B.get(j) > m)54 --j;55 count += j + 1;56 }57 return count;58 }59}60