1

The task: Implement an algorithm to determine if a string has all unique characters.

I wrote two functions that dose that. How do I start to asses which one is better/more efficient? what are the things to look for?

this is the first one:

def is_unique(word):
    start = 0
    len_word = len(word)

    while start < len_word:
        for i in range(start + 1, len_word):
            if word[start] == word[i]:
                return False
        start += 1
    return True

second one:

def unique_list(word):
    unique = []

    for i in word:
        if i in unique:
            return False
        else:
            unique += i
     return True

1 Answer 1

2

Both algorithms are inefficient: their complexity is O(n^2) with n the number of character in word. The second algorithm will be a bit faster in practice because it uses the build-in Python operation i in unique (rather than slow CPython loops).

The test can be done in a much faster way: len(set(s)) == len(s). This line tests if the string contains unique characters in O(n) (since the string characters can be converted to a set in linear time).

Sign up to request clarification or add additional context in comments.

1 Comment

Your solution is so elegant! And the performance must be quite optimal in the general case since all the work is done in the set constructor, implemented in executable code. Yet for long strings with duplicate characters coming early in the string, both approaches by the OP will return false quicker. Constructing the set incrementally might be more appropriate if duplicates are more likely to occur than not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.