Noble Integer InterviewBit

 Problem Description

Given an integer array A, find if an integer p exists in the array such that the number of integers greater than p in the array equals to p.



Input Format

The first and only argument is an integer array A.



Output Format

Return 1 if any such integer p is found else return -1.



Example Input

Input 1:

 A = [3, 2, 1, 3]

Input 2:

 A = [1, 1, 3, 3]



Example Output

Output 1:

 1

Output 2:

 -1



Example Explanation

Explanation 1:

 For integer 2, there are 2 greater elements in the array. So, return 1.

Explanation 2:

 There is no such integer exists.

Solution:

class Solution:
# @param A : list of integers
# @return an integer
def solve(self, A):
    A=sorted(A)
    n=len(A)
    if A[-1]==0:
        return 1
       
        
        for i in range(n-1):
            if A[i]==A[i+1]:
                continue
            elif A[i]==n-i-1:
                return 1
        return -1
    

Screenshot:




Things we need to understand:

arithmetic is better than len()
At first, I used len(A[i-1:]) to find the remaining elements it has given me a time complexity then I modified it to n-i-1 where n is len of the list.

0 is the corner test case we need to consider, if 0 is present at the end of the sorted list then we don’t have any other elements greater than the 0 its true right so we should return 1









Comments

Popular posts from this blog

Trouble with the Number System

Residue Arithmetic

Perfect Peak of Array