Kotlin
programming
array manipulation
duplicates removal
string handling

How to remove duplicate strings from an array in Kotlin

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

In programming, it's common to encounter scenarios where you have an array or list containing duplicate elements, and you need to ensure that all elements are unique. Kotlin, being a modern and expressive language, provides several ways to remove duplicate strings from an array. This article will delve into various methods to effectively remove duplicates, along with technical explanations and examples.

Methods to Remove Duplicate Strings from an Array in Kotlin

1. Using distinct()

Kotlin's List interface provides the distinct() function, which returns a new list containing only unique elements from the original list.

kotlin
1fun removeDuplicatesUsingDistinct(array: Array<String>): List<String> {
2    return array.toList().distinct()
3}
4
5fun main() {
6    val stringArray = arrayOf("apple", "orange", "apple", "banana", "orange")
7    val uniqueStrings = removeDuplicatesUsingDistinct(stringArray)
8    println(uniqueStrings)  // Output: [apple, orange, banana]
9}

Explanation:

  • Array to List Conversion: The toList() function converts an array into a list. This is necessary because distinct() is available on lists, not arrays.
  • Distinct Elements: The distinct() function internally uses a set to filter out duplicates, hence it depends on the elements' equals() and hashCode() methods.

2. Using a Set

A Set is a collection that inherently does not allow duplicate elements. We can convert an array to a set and then back to a list or array to achieve uniqueness.

kotlin
1fun removeDuplicatesUsingSet(array: Array<String>): List<String> {
2    return array.toSet().toList()
3}
4
5fun main() {
6    val stringArray = arrayOf("apple", "orange", "apple", "banana", "orange")
7    val uniqueStrings = removeDuplicatesUsingSet(stringArray)
8    println(uniqueStrings)  // Output: [apple, orange, banana]
9}

Explanation:

  • Conversion to Set: The toSet() function converts the array to a set, automatically removing duplicates.
  • Re-conversion to List: Using toList() after toSet() gives us a collection back that we can manipulate further in Kotlin.

3. Using a Loop with a Mutable Set

For more control, you might use a loop to manually traverse the array and insert elements into a MutableSet.

kotlin
1fun removeDuplicatesUsingLoop(array: Array<String>): List<String> {
2    val seen = mutableSetOf<String>()
3    val uniqueList = mutableListOf<String>()
4
5    for (item in array) {
6        if (seen.add(item)) {
7            uniqueList.add(item)
8        }
9    }
10
11    return uniqueList
12}
13
14fun main() {
15    val stringArray = arrayOf("apple", "orange", "apple", "banana", "orange")
16    val uniqueStrings = removeDuplicatesUsingLoop(stringArray)
17    println(uniqueStrings)  // Output: [apple, orange, banana]
18}

Explanation:

  • MutableSet for Tracking: As we iterate through the array, we attempt to add each item to a MutableSet. Since sets do not allow duplicate entries, add(item) will return true only for unique items.

Key Considerations

  • Performance: All methods leverage the Set interface, meaning they have an average time complexity of O(n)O(n), where nn is the number of elements in the array.
  • Order Preservation: The order of elements is preserved in each of these methods. The first occurrence of each element is retained.

Comparison Table

MethodDescriptionOrder PreservationPerformance
distinct()Uses Kotlin's distinct function to filter duplicates.YesO(nlog(n))O(n \cdot log(n))
Set ConversionConverts array to set and back.YesO(nlog(n))O(n \cdot log(n))
Loop with MutableSetUses a loop with a set to filter duplicates manually.YesO(n)O(n)

Additional Details:

  • Use Case Specifics: If thread safety is a concern, consider synchronizing access to your data structures or using concurrent collections.
  • Null Values: These methods will correctly handle null values in the array. null will be considered as a valid unique element.
  • Data Types: While this article focuses on String arrays, the same methods can be applied to any data type as long as they have properly implemented equals() and hashCode().

By leveraging Kotlin's robust collection framework, handling duplicates in arrays can be done efficiently and concisely, simplifying many data processing tasks.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.