简体   繁体   中英

How can I calculate the time complexity of this code?

I'm going through HackerRank problems and I have this question:

Given a list of minerals embedded in each of John's rocks, display the number of types of gemstones he has in his collection. For example, the array of mineral composition strings is ['abc', 'abc', 'bc]. The minerals b and c appear in each composite, so there are 2 gemstones.

I have a solution, but I would like to ask about the time complexity:

def gemstones(arr):
    counter = 0
    char_set = set(''.join(arr))
    for ch in char_set:
        if all(ch in word for word in arr):
            counter+=1
    return counter

Am I right in thinking that the time complexity is O(n+m) where n is the number of elements in char_set and m is number of elements in arr?

The correct complexity is O(N):

def gemstones(arr) :
    return len(set(arr))

This will return the correct number of gemstones, ignoring the duplicates.

You don't have to count the minerals for that.


Below there's a link to the HR problem, for that problem the solution is:

def gemstones(arr):
    x = set(arr[0])
    for a in arr :
        x.intersection_update(set(a))
    return len(x)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM