Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way to find if an array is a permutation

A non-empty array A consisting of N integers is given.

A permutation is a sequence containing each element from 1 to N exactly once each. For example, [4,2,1,3] is a permutation, but [4,1,3] is not a permutation, because value 2 is missing.

The goal is to check whether the input array A is a permutation.

constraints

  • N is an integer within the range [1..100,000];
  • Each element of A is an integer within the range [1..1,000,000,000].

My code:

# 1 = permutation 0 = not a permutation
def solution(A):
    total = sum(A)

    formula_total = (len(A)*(len(A)+1))/(2)

    if total == formula_total:

        return 1

    return 0

my solution is failing on Antisum (I don't know what that is )

like image 825
Harpreet Singh Avatar asked Dec 17 '22 19:12

Harpreet Singh


1 Answers

You can then check if the minimum value of the list is 1 and if the maximum value is equal to the length of the list. You can then convert the list to a set to check if the length is equal, and if so, all items in the list are unique and therefore the list is what you consider a permutation:

def solution(A):
    return min(A) == 1 and max(A) == len(A) == len(set(A))

so that:

print(solution([4,2,1,3]))
print(solution([4,1,3]))
print(solution([4,2,1,4]))
print(solution([4,2,5,3]))

outputs:

True
False
False
False

If you want 1 and 0 as the returning value you can pass the Boolean value to the int() constructor instead:

def solution(A):
    return int(min(A) == 1 and max(A) == len(A) == len(set(A)))
like image 51
blhsing Avatar answered Dec 20 '22 08:12

blhsing