Categories: Algorithmpython

Unique Characters in String using Python

Problem

Given a string,determine if it is compressed of all unique characters. For example, the string ‘abcde’ has all unique characters and should return True. The string ‘aabcde’ contains duplicate characters and should return false.

Solution

We’ll see two possible solutions, one using a built-in data structure and a built in function, and another using a built-in data structure but using a look-up method to check if the characters are unique.

def uni_char(s):
    return len(set(s)) == len(s)
def uni_char2(s):
    chars = set()
    for let in s:
        # Check if in set
        if let in chars:
            return False
        else:
            #Add it to the set
            chars.add(let)
    return True

Test Your Solution

"""
RUN THIS CELL TO TEST YOUR CODE
"""
from nose.tools import assert_equal


class TestUnique(object):

    def test(self, sol):
        assert_equal(sol(''), True)
        assert_equal(sol('goo'), False)
        assert_equal(sol('abcdefg'), True)
        print('ALL TEST CASES PASSED')
        
# Run Tests
t = TestUnique()
t.test(uni_char)

ALL TEST CASES PASSED

Recommended: Understand Big-O Notation Complexity Of Algorithm

Follow Me ❤😊

If you like my post please follow me to read my latest post on programming and technology.

Instagram

Facebook

Recent Posts

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

1 month ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

2 months ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

2 months ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

3 months ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

3 months ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

3 months ago