Skip to content

How to Find the Unique String in Python

The challenge

There is an array of strings. All strings contain similar letters except one. Try to find it!

find_uniq([ 'Aa', 'aaa', 'aaaaa', 'BbBb', 'Aaaa', 'AaAaAa', 'a' ]) # => 'BbBb' find_uniq([ 'abc', 'acb', 'bac', 'foo', 'bca', 'cab', 'cba' ]) # => 'foo'
Code language: Python (python)

Strings may contain spaces. Spaces are not significant, only non-spaces symbols matter.
E.g. A string that contains only spaces is like an empty string.

It’s guaranteed that the array contains more than 3 strings.

The solution in Python code

Option 1:

def find_uniq(arr): arr.sort(key=lambda x: x.lower()) arr1 = [set(i.lower()) for i in arr] return arr[] if arr1.count(arr1[]) == 1 and str(arr1[]) != 'set()' else arr[-1]
Code language: Python (python)

Option 2:

def find_uniq(arr): for word in set(arr): for letter in set(word): if sum([1 if letter in w else for w in arr]) == 1: return word else: continue
Code language: Python (python)

Option 3:

from collections import Counter def find_uniq(arr): res = Counter(''.join(arr)).most_common() return ''.join([x for x in arr if res[-1][] in x])
Code language: Python (python)

Test cases to validate our solution

test.describe('should handle sample cases') test.assert_equals(find_uniq([ 'Aa', 'aaa', 'aaaaa', 'BbBb', 'Aaaa', 'AaAaAa', 'a' ]), 'BbBb') test.assert_equals(find_uniq([ 'abc', 'acb', 'bac', 'foo', 'bca', 'cab', 'cba' ]), 'foo') test.assert_equals(find_uniq([ ' ', 'a', ' ' ]), 'a')
Code language: Python (python)

See also  [Solved] Instance Profile already exists in Terraform
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x