One is permutation of the other

Problem: Given two strings, write a method to decide if one is a permutation of the other

def isPermutation(str1,str2):
    if len(str1) != len(str2):
        return False
    else:
        str1Sorted = "".join(sorted(str1))
        str2Sorted = "".join(sorted(str2))
        if str1Sorted == str2Sorted:
            return True
        else:
            return False

print isPermutation("god","dog")
print isPermutation("god","logged")

def isPermutation2(str1,str2):
    if len(str1) != len(str2):
        return False
    else:
        isPerm = True
        arr = [0]*256
        for entries in str1:
            arr[ord(entries)] += 1

        for entries in str2:
            arr[ord(entries)] -= 1

        for entries in arr:
            if entries != 0:
                isPerm = False
   return isPerm

print isPermutation("god","dog")
print isPermutation("god","logged")

Advertisement

Unique Characters

Problem: Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?

def isUniqueChars(str):
    #first sort the string O(nlgn)
    sortedStr = "".join(sorted(str))

    isUnique = True

#compare the consecutive characters O(n)
for i in range(len(sortedStr)-1):
if sortedStr[i] == sortedStr[i+1]:
isUnique = False

return isUnique

print isUniqueChars("Amber".lower())
print isUniqueChars("madam".lower())

def isUniqueChars2(str):
#considering the characters are ascii characters building an array for 256 characters acting as a hash table
arr = [0]*256
for c in str:
asciiValue = ord(c)
arr[asciiValue] += 1

isUnique = True

#checking for repeated characters O(1)
for entries in str:
if arr[ord(entries)] > 1:
isUnique = False
return isUnique

print isUniqueChars2("Amber".lower())
print isUniqueChars2("madam".lower())