Program to find number of elements in A are strictly less than at least k elements in B in Python

PythonServer Side ProgrammingProgramming

Suppose we have two lists of numbers A and B, and another value k, we have to find the number of elements in A that are strictly less than at least k elements in B.

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.

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 i in A, do
    • if i < B[k - 1], then
      • ct := ct + 1
  • return ct

Let us see the following implementation to get better understanding −

Example

 Live Demo

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))

Input

[6, -2, 100, 11], [33, 6, 30, 8, 14], 3

Output

3
raja
Published on 19-Nov-2020 11:02:12
Advertisements