Home > Software design >  Function to check if an Array contains N numbers
Function to check if an Array contains N numbers

Time:12-13

I need to define a function with Python where given a non-empty array A of N (sorted in non-decreasing order) integers and integer K, checks whether A contains numbers 1, 2, …, K (every number from 1 to K at least once) and no other numbers.

This is the function I wrote, but I am getting some unexpected errors as:

print(solution([1,2,3,4,5,5,5,6,7,8,8,9,10,10,11,11,11,11,13,14,14,15], 15))
True

Above should be FALSE, 12 is missing

Function:

def solution(A, K):
    n = len(A)
    for i in range(K-1):
        if (A[i] != A[i   1] and A[i]   1 != A[i   1]):
            return False
    if (A[0] != 1 or A[n - 1] != K):
        return False
    else:
        return True

Any ideas how to solve it changing a max of 2 lines from the code above? Thank you

PD: Working for the moment

def solution(A, K):
n = len(A)
for i in range(n - 1):
    if (A[i] != A[i   1] and A[i]   1 != A[i   1]):
        return False
if (A[0] != 1 or A[n - 1] != K):
    return False
else:
    return True

CodePudding user response:

This works:

def isInArray(el, arr):
  for i in arr:
    if el == i: return True
  return False

def solution(arr, k):
  l = len(A)
  if l < k: return False
    
  for i in range(1, k 1):
    if not isInArray(i, arr): return False
  
  return True

CodePudding user response:

Use sets:

set(A) == set(range(1, K 1))

Example:

A = [1, 3, 2, 2, 4, 5, 1]
B = [1, 2, 2, 4, 5, 1]    # 3 is missing
C = [1, 3, 9, 2, 4, 5, 1] # 9 is extra
K = 5

set(A) == set(range(1, K 1))
# True

set(B) == set(range(1, K 1))
# False

set(C) == set(range(1, K 1))
# False

using a loop

This is assuming that the input list is sorted!

def solution(l, k):
    prev = 0
    for x in l:
        if x > k or x > prev 1:
            return False
        prev = x
    return True
    
solution([1,2,3,4,5,5,5,6,7,8,8,9,10,10,11,11,11,11,13,14,14,15], 15)
# False
solution([1,2,3,4,5,5,5,6,7,8,8,9,10,10,11,11,11,12,13,14,14,15], 15)
# True
solution([1,2,3,4,5,6], 5)
# False

CodePudding user response:

if space complexity of O(N) is allowed then here is a solution

# your code goes here
def solution(A, K):
    array = [0 for i in range(K 1)]
    for i in A:
        if i>K or i<1:
            return False
        array[i]  = 1
    
    count = 0
    for i in array[1:]:
            if i==0:
                return False
    return True
  • Related