# String Duplicate Characters – Assignment Sample

When reading through this sample on string duplicate characters, students can find ideas on how to solve their own problems. The benefit of our samples is obvious, because they help students to deal with their own homework. In the sample you will read further, you will find our expert’s ideas which can’t be presented as your own. You can find more samples on AssignmentShark.com. While working on your assignment, you can face some difficulties. Numerous students ask us to help them with their homework.

If you have a large amount of assignments, you can leave them to our expert. The reason why students get our help is that they can save time and effort. The purpose of our site is to help students with any type of assignment. You just need to place your order, mentioning your requirements and setting the deadline. So, read through the following sample and see how our expert adheres to the academic standards while completing the specific assignment!

## Duplicate Characters in the String

In carrying out this task, the additional data structures can not be used.

One of the obvious ways to solve this problem is to compare each character of the string to any other character. It requires O(n²) time and O (1) memory.

If we can change the string, it is possible to sort it (which will require O(nlogn) time), and then sequentially verify the identity of adjacent characters. Be careful: some sorting algorithms require large amounts of memory.

We can slightly optimize the task: return false if the length of the string exceeds the number of characters in the alphabet. In the end, a row with 280 unique characters can not exist if there are only just 256 characters. However, if it is Unicode-string, this optimization will not help.

Our solution is to create an array of boolean values, where the flag with index i changes if the string contains the chosen symbol. If you “stumble” on the same character for the second time, you can immediately return false.

The code that implements this algorithm is as follows:

```public boolean unique(String s) {
boolean[] chars = new boolean[256];
for (int i = 0; i < s.length(); i++) {
int k = s.charAt(i);
if (chars[k]) {        //symbol was found
return false;
}
chars[k] = true;
}
return true;
}

```

Evaluation of the execution time of this code is O(n), where n is the length of the string, and the evaluation of the required memory is O(1).

You can reduce memory usage using a bit vector. In the next example, we assume that the string has only lowercase characters a-z. This allows us to use just one value of type int.

```public boolean unique(String s) {
int c = 0;
for (int i = 0; i < s.length(); i++) {
int k = s.charAt(i) - 'a';
if (c & (1 << k)) > 0) {
return false;
}
c |= (1 << k);
}
return true;
}
```

Choosing the best solution is based on the additional restrictions of a specific task.