This solution only uses Arrays:
import java.util.Scanner;
import java.util.Arrays;
public class DeleteEquals {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int arrSize = 10;
String[] sortedResult = new String[arrSize];
String[] result = new String[arrSize];
Map<String, Integer> originalIndexMap = new HashMap<>();
for (int i = 0; i < arrSize; i++) {
String currentResult = sc.nextLine();
sortedResult[i] = currentResult;
if (originalIndexMap.get(currentResult) == null) {
//store the index of the first appearance of currentResult
originalIndexMap.put(currentResult, i);
}
}
//sorting array with "quicksort" to reduce the time to find the duplicates (time will be O(n * log n) with quicksort)
Arrays.sort(sortedResult);
String previousResult = null;
for (int i = 0; i < arrSize; i++) {
String currentResult = sortedResult[i];
if (currentResult != null && currentResult != previousResult) {
//currentResult is unique because of the sorting
previousResult = currentResult;
//originalIndexMap stores the index of the first appearance of the currentResult string. We should store currentResult by the index of the first appearance to preserve user input order
result[originalIndexMap.get(currentResult)] = currentResult;
} else {
//duplicate or null: ignore it
}
}
for (int i = 0; i < arrSize; i++) {
//with originalIndexMap we preserve the order of the user input in the result array
String currentResult = result[i];
if (currentResult != null) {
System.out.println(currentResult);
} else {
//null value corresponds to null or duplicate value in the original result: should be ignored
}
}
}
}
This solution will have O(n * log n) time function, due to implementation of Arrays.sort() in java.util.Arrays (they use "quicksort" by default).
We have to use 4 iterations:
1. first iteration will initialise sortedResult and originalIndexMap
2. second iteration will sort the elements in the sortedResult, using Arrays.sort()
3. third iteration will remove duplicates and insert unique not-null elements in result array by putting it at the index of the first appearance of the element in the user input
4. fourth iteration will output result array, ignoring null values, which correspond to null or duplicate elements in the original input
So if the number of elements is n, this algorithm will require:
1. (3 * n) elements in stack memory
2. O(n) time in the first iteration
3. O(n log n) time for sorting array
4. O(n log n) time for storing elements to result array (map search gives us O(log n) for each element here)
5. O(n) for result output
Total time function of this algorithm is O(n) + O(n log n) + O(n log n) + O(n), which is equivalent to O(n log n)
Total memory footprint of this algorithm is equivalent to 3n
Set: looking up an element both in theTreeSetandHashSetimplementation takesO(log n).