Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find number of elements in A are strictly less than at least k elements in B in Python
When working with two lists of numbers, we sometimes need to find how many elements from the first list are strictly smaller than at least k elements in the second list. This problem can be solved efficiently by sorting and comparison.
So, if the input is like A = [6, -2, 100, 11], B = [33, 6, 30, 8, 14], k = 3, then the output will be 3, as -2, 6, and 11 are strictly less than 3 elements in B.
Algorithm
To solve this, we will follow these steps −
- if k is same as 0, then
- return size of A
- sort B in reverse order
- ct := 0
- for each element in A, do
- if element < B[k - 1], then
- ct := ct + 1
- if element < B[k - 1], then
- return ct
Example
Let us see the following implementation to get better understanding −
class Solution:
def solve(self, A, B, k):
if k == 0:
return len(A)
B.sort(reverse=True)
ct = 0
for i in A:
if i < B[k - 1]:
ct += 1
return ct
ob = Solution()
A = [6, -2, 100, 11]
B = [33, 6, 30, 8, 14]
k = 3
print(ob.solve(A, B, k))
3
How It Works
The algorithm works by first sorting list B in descending order. After sorting, B becomes [33, 30, 14, 8, 6]. The element at position k-1 (which is B[2] = 14) represents the k-th largest element in B. Any element in A that is strictly less than this value will be strictly less than at least k elements in B.
Step-by-Step Execution
A = [6, -2, 100, 11]
B = [33, 6, 30, 8, 14]
k = 3
# Step 1: Sort B in reverse order
B_sorted = sorted(B, reverse=True)
print("Sorted B:", B_sorted)
# Step 2: Find k-th largest element (at index k-1)
kth_largest = B_sorted[k-1]
print(f"The {k}-th largest element in B: {kth_largest}")
# Step 3: Count elements in A that are strictly less than kth_largest
count = 0
for element in A:
if element < kth_largest:
print(f"{element} < {kth_largest}: True")
count += 1
else:
print(f"{element} < {kth_largest}: False")
print(f"Total count: {count}")
Sorted B: [33, 30, 14, 8, 6] The 3-th largest element in B: 14 6 < 14: True -2 < 14: True 100 < 14: False 11 < 14: True Total count: 3
Edge Cases
# Case 1: k = 0 (all elements in A qualify)
ob = Solution()
print("k=0:", ob.solve([1, 2, 3], [4, 5, 6], 0))
# Case 2: No elements in A qualify
print("No qualifying elements:", ob.solve([50, 60, 70], [1, 2, 3], 2))
# Case 3: All elements in A qualify
print("All qualifying elements:", ob.solve([1, 2, 3], [10, 20, 30], 2))
k=0: 3 No qualifying elements: 0 All qualifying elements: 3
Conclusion
This algorithm efficiently solves the problem in O(n log n) time by sorting list B and comparing each element in A with the k-th largest element. The key insight is that if an element is smaller than the k-th largest element, it's automatically smaller than at least k elements.
