Algorithm to determine if array contains n…n+m?

前端 未结 30 3177
清酒与你
清酒与你 2020-11-28 01:45

I saw this question on Reddit, and there were no positive solutions presented, and I thought it would be a perfect question to ask here. This was in a thread about interview

30条回答
  •  时光说笑
    2020-11-28 02:04

    In Python:

    def ispermutation(iterable, m, n):
        """Whether iterable and the range [n, n+m) have the same elements.
    
           pre-condition: there are no duplicates in the iterable
        """ 
        for i, elem in enumerate(iterable):
            if not n <= elem < n+m:
                return False
    
        return i == m-1
    
    print(ispermutation([1, 42], 2, 1)    == False)
    print(ispermutation(range(10), 10, 0) == True)
    print(ispermutation((2, 1, 3), 3, 1)  == True)
    print(ispermutation((2, 1, 3), 3, 0)  == False)
    print(ispermutation((2, 1, 3), 4, 1)  == False)
    print(ispermutation((2, 1, 3), 2, 1)  == False)
    

    It is O(m) in time and O(1) in space. It does not take into account duplicates.

    Alternate solution:

    def ispermutation(iterable, m, n): 
        """Same as above.
    
        pre-condition: assert(len(list(iterable)) == m)
        """
        return all(n <= elem < n+m for elem in iterable)
    

提交回复
热议问题