[Challenge] Unique Characters in a String



Tested it, it accounts for those characters too.


/*Begin PHP Code to identify if string contains duplicates*/
print_r("all unique");
print_r("duplicates found.");
/*End Code to identify if string contains duplicates*/
Code explaination:
1. Break the input string into a numerically indexed array where characters of string are stored as the array values.
2. Next, flip the array of characters created in previous step so that the values and keys are exchanged. Example if the first index in the array is '0' and it stores the character value of 'w' (assuming our string starts with the first character 'c' as in the string 'character', then after the flip, the resultant flipped array will contain the key 'c' with a corresponding value '0'.
3. The above flipped array is guaranteed to have unique keys which are nothing but our characters in the string. So, in the example string of 'character' where the characters 'c' ,'a' and 'r' are duplicated, the flipped array will have only unique one instance of these characters stored as keys. Ergo, our resultant flipped array wil have as its keys the unique characters 'c','h','a','r','t','e','s'
4. The count or size of the flipped array above will be either equal to the length of the original string or less. If the count of the array is less than the original string length, it would indicate that there were duplicates that got eliminated after the flipping stage and if the count of the flipped array and length of string are same, then it would indicate that there were no duplicate characters in our input string.


I've made a Ruby solution.

First approach

def unique_string(string)
  if string.chars.sort.uniq.length == string.length
    puts "all unique"
    puts "duplicates found." # Is the dot a typo?

This is not optimal, but my preferred solution. The following functions create new structures: chars, sort, uniq.

After reading the solutions, I've realised it's almost identical to @megaplayer01856 's solution in Python.


I've also made an intermediate solution.

def unique_string(string)
  string.each_char { |char|
    if string.count(char) > 1
      puts "duplicates found." # Is the dot a typo?
  puts "all unique"

It's not building a new structure, also I consider it as an O(n) algorithm.


I decided to use a list comprehension (a way to perform functions on every item in an iterable, every character in a string in this case) to solve this problem and keep it brief while also preserving readability.

My first idea for the inner workings of this functions were:

  1. Use a list comprehension to get the occurrences of each character in string.
  2. Check if the maximum (max()) occurrence is 1. If so, every character is unique.
  3. Print the result.

This is the first draft of my function, written from scratch:

def print_uniqueness(string):
    """Print whether any character in the string occurs more than once."""
    occurrences = [string.count(char) for char in string]
    if max(occurrences) == 1:
        print('all unique')
        print('duplicates found')

The last four lines can be cleaned up with a variable and a ternary operator, so the final form of this function looks like this:

def print_uniqueness(string):
    """Print whether any character in the string occurs more than once."""
    occurrences = [string.count(char) for char in string]
    is_unique = max(occurrences) == 1
    print('all unique' if is_unique else 'duplicates found')

The function can then be called with a quick print_uniqueness(input()) and bam!

I don't feel any readability is lost by using a single-line if/else statement in this context, especially when the condition is reformatted into its own variable. Since any comments feel like they'd just be restating what the code does (I try to abide by the "make your code its own comment" practice), and since the code is still fundamentally understandable even for people who aren't necessarily familiar with list comprehensions or the ternary operator, I think this is about the perfect balance of readable and compact.

Just for laughs here's a one-liner version:

def print_uniqueness(string): print('all unique' if max(string.count(char) for char in string) == 1 else 'duplicates found')


This is a simple one-liner with ES6 JavaScript.

console.log('str' == [...new Set('str')].join('') ? 'all unique' : 'duplicates found');


Bash Script in 1 line

if [ $(echo "any given string" | sed 's|\(.\)|\1\n|g' | sort | uniq  -d  | wc -l) == 0  ] ; then echo "all unique"; else echo "duplicates found."; fi


sed : modify string to multiline, 1 character per string
sort : sort the line
uniq -d : display duplicate line
wc -l : provide number of line

 public void checkString(String input) {
    	boolean dupFound = false;
    	for ( int i = 0; input != null && i < input.length(); i++ ) {
    		int count = input.length() - input.replace( Character.toString(input.charAt(i)), "").length();
    		if ( count > 1 ) {
    			dupFound = true;
    	if ( !dupFound ) {
    		System.out.println("all unique");
    	} else {
    		System.out.println("duplicates found");

//loops over the length of the string checking if each character is in there more than once


There are two useful string methods in JavaScript: indexOf and lastIndexOf. If a symbol of string is unique, they both return the same value.

function isEveryCharUnique(string) {
for (i=0; i<string.length; i++) {
if (string.indexOf(string[i]) !== string.lastIndexOf(string[i])) {return console.log("duplicates found")}
return console.log("all unique")}


PHP Solution:

I used the PHP function str_split() to compare the count of the return value against the count of the same array gone through array_unique which removes all duplicates.

If count is of original string-array (o.O) is bigger then the one gone through array_unique there has to be dublicates.

function checkDuplicatesInString(string $string) : string
    return str_split($string) > array_unique(str_split($string)) ? "duplicates found." : "all unique";

echo checkDuplicatesInString("abcdefghijklmnopqrstuvwxyz");
=> all unique

echo checkDuplicatesInString("abcddefghijklmnopqrstuvwxyz");
=> duplicates found

Solution for extra Credit without additional Datastructure.
The return of preg_match returns 1 in case of match

function checkDuplicatesInStringNoExtra(string $string) : string
    return (preg_match("/(.)(?=.*?\1)/", $string) == 1) ? "duplicates found." : "all unique";
echo checkDuplicatesInString("abcdefghijklmnopqrstuvwxyz");
=> all unique

echo checkDuplicatesInString("abcddefghijklmnopqrstuvwxyz");
=> duplicates found

best Regards


def challenge(string):
    print('all unique' if len(list(string))==len(set(string)) else 'duplicates found')


Probably not the most elegant way to do it but it does the job.


import sys

word = raw_input()

for x in range(0, len(word)):
	tempWord = word[:x] + word[x+1:]
	if word[x] in tempWord:
		print 'duplicates found'

print 'all unique'


For my first attempt was so natural think to use set(). So I decided to avoid any additional data structures:

def unique(string):
	for i in range(len(string)):
		if i != string.find(string[i]):
			return "duplicates found" 
	return "all unique"

For any character in the string i check if its position is egual to the the lowest index in the string where the character is found: if not a duplicate has been occurred.


A really cool approach, but I guess to make it complete you need to change the regEx to:
But still really nice!!!


I think my solution is pretty simple and sort of brute force, because it simply sorts all characters in the string, and the compare each character with the next character.

I actually have been using a similar approach proffessionally at my current job to compare different versions of "legal" text section. By sorting all charaters in both versions of a text and eliminating equal characters in te to versions, you get an estimate of how many charaters have been changed. I you move Words arround in the text they will still be sorteret the way and are not considered a change when estimating. The result can also be used to find text sections that seems to be equal or almost equal.

My solution

def containsDuplicateCharaters(text1):
    result1 = 'all unique.'
    len1 = len(text1)
    if len1 > 1:
        work1 = sorted(text1)
        for i1 in range(1, len1-1):
            if work1[i1] == work1[i1-1]:
                result1 = 'duplicates found.'
    print result1
containsDuplicateCharaters("hans christian studt")
containsDuplicateCharaters("hans c1ri2t345678ud9")

Hans Christian Studt


Simple in perl - is to split the string and look for duplicates. By using a hash we can keep track of letters...
The ++ postfix only increments the value after it is checked. This is a common perl technique...

sub uni {
  my %x;
  foreach( split //, shift ) { ## Split into individual characters
    return q(duplicates found) if $x{$_}++; ## Add 1 to count of character - but return dup if already seen
  return q(All unique); ## All uniqu so return message.


This is probably an awful stab at this but here goes. This is just based on the fact that if a character is unique in the string then the string methods indexOf() and lastIndexOf() would return the same value, as a unique character is both the first and last instance of said character in the string.

This function loops through the string characters and returns immediately upon finding a character where the first and last indexes don't match (meaning there's more than one instance of the character). If the loop reaches the end without already returning then it will return with "all unique".

function unique_string(s) {
	for (var i=0; i<s.length; i++) {
		if (s.indexOf(s.charAt(i)) !== s.lastIndexOf(s.charAt(i))) {
			return "duplicates found";
	return "all unique";

I think this might fulfill the intermediate too?


I am from C++ background. Will update my solution soon with python and also extending it to support unicode characters. This C++ solution only works for input with ASCII characters (full 256).

Idea is to keep track of characters we see and set the appropriate bool array element to true. This solution runs in O(n) and uses constant space O(1). This function exits when it sees the first duplicate character from the input string or when all unique characters are read.

bool is_string_unique (const std::string & input)
   // Array to hold the unique characters count
   const int MAX_ASCII_CHARACTERS = 256;
   bool seen_char[MAX_ASCII_CHARACTERS];
   memset(seen_char, false, sizeof seen_char);

   // Get input string size
   std::string::size_type i, strsize = input.size();

   for (i = 0; i < strsize; i++) 
      unsigned char index = (unsigned char) input[i];
      if (seen_char[index])
         std::cout << "duplicates found\n";
         return false;

      // Set this character in seen_char
      seen_char[index] = true; 
   std::cout << "all unique\n";
   return true;


I used JavaScript, because this is my everyday language and the most useful for myself to learn more about.
My explanation is in the comments in the code

var characters = " !#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~"+String.fromCharCode(92); // all js characters
var len = characters.length; // length of character string

for (var i=0; i<100; i++) { // do the functions 100 times

// function to make a random string made out of characters of the character string
function randomString() {
    var randomLen = Math.round(Math.random()*len); // random length of string (max length of character string)
    var RandomString = ""; // empty string
    for (var i=0; i<randomLen; i++) { 
        var randomNumber = Math.round(Math.random()*len); // random integer (max length of character string)
        var randomCharacter = characters[randomNumber]; // choose the character on the nth (random number) location in the random string
        RandomString += randomCharacter; // add randomCharacter to make the random string
    return RandomString;

// edited a function that returns only the unique values of an array (that i found somewhere on stackoverflow longer ago) to a function that checks if there are unique characters in a string.
function checkUnique(string) {
    var unique = {};
    var distinct = ""; // empty string
    for(var i in string ) { // go through every character in the string
        key = string[i]; // key is the current character from the string
        if(typeof(unique[key]) == "undefined") { // if this key is undefined in the unique object
            distinct += key; // then it is added to the distingt string as an unique value
        unique[key] = 0; // after this key has been checked, it is set to zero in the unique object
    var result = string == distinct ? "all unique" : "duplicates found"; // if the distinct string is the same as the beginning string, then all characters in the string are unique. 
    console.log(result); // print "all unique" or "duplicates found"


Since ECMAScript 6 there is this nice script method includes() in Javascript

so I am using it

function sTest gets given string from calling
then using method includes from start position which is changet incrementaly by loop counting from string length to 0
if duplication founded return message string - founded
else if not founded return message string - unique
could be true or false but then you need another statement check
this way you just call function with print command

function sTest(gString){
 var i = gString.length;
  do { 
     return ("duplicates found.");
  while (i > 0);
   return ("all unique"); 

then you can call it perhaps this way



JavaScript (.includes is not yet available in IE, could use indexOf)

Uses the hardly used .reduce Array method

function isunique(str) {
    if (str === str.split('').reduce((uniqueletters, letter) => {
            if (!uniqueletters.includes(letter)) uniqueletters.push(letter);
            return uniqueletters;
        }, []).join('')) {
        return "all unique";
    } else {
        return "duplicates found";