Hello! Today, we will cover set problems that frequently appear in coding tests using Swift. A set is a data structure that collects non-duplicate elements and is useful for various problems. In this lecture, we will express sets and enhance our algorithmic thinking through problems utilizing them.
Problem Description
Write a function that returns all unique numbers from a given integer array in the form of a set. In other words, it should remove any duplicate numbers contained in the input array and return a set of unique numbers.
Example Problem
Input: [1, 2, 2, 3, 4, 4, 5]
Output: [1, 2, 3, 4, 5]
Constraints
- The length of the input array is between 1 and 10,000.
- Numbers are between -1,000,000 and 1,000,000.
Algorithm Approach
This problem can be solved with a simple approach as follows:
- Utilize Swift’s Set to collect the input array and remove duplicates.
- Add the elements of the array to the Set. Since a Set does not allow duplicate values, all duplicates will be removed automatically.
- Finally, convert the Set back to an array and return the result.
Swift Code Implementation
Below is the Swift code to solve the problem:
func uniqueElements(from array: [Int]) -> [Int] {
let uniqueSet = Set(array)
return Array(uniqueSet)
}
let inputArray = [1, 2, 2, 3, 4, 4, 5]
let result = uniqueElements(from: inputArray)
print(result) // [2, 3, 4, 5, 1]
Code Explanation
Let’s take a closer look at the code above:
- Define the function
uniqueElements(from:)
. This function takes an integer array as input and returns an array of unique elements. - Call
Set(array)
to add all the elements of the input array to the set. During this process, duplicates are automatically removed due to the properties of Set. - Convert the Set back to an array using
Array(uniqueSet)
. The final result will be an array consisting of distinct elements.
Test Cases
You can test the function above with various input values to verify its correct operation:
print(uniqueElements(from: [1, 1, 1, 1])) // [1]
print(uniqueElements(from: [1, 2, 3, 3, 3, 2, 1])) // [1, 2, 3]
print(uniqueElements(from: [])) // []
Conclusion
In this lecture, we learned how to solve the problem of removing duplicate elements using Swift’s set. Sets enhance the conciseness of the code and help effectively manage duplicate data. I hope you practice using sets in various coding test problems to become a better programmer. Thank you!