Problem solving using Swift: Part 3

Varun Tomar
2 min readMay 22, 2020
Photo by Olav Ahrens Røtne on Unsplash

Continuing Part 2. As promised to come up with new problem statements and their solutions daily, we are going to solve more problems today. You can follow me for to get fresh articles every day.

Problem Statement 6 : Write an extension of “sequence” to remove duplicates from it, provided order of elements would not get change.

Solution : In case of duplicates first thought comes in mind is of “Set”, as set can remove duplicates. But here we also need to maintain ordering of elements🤔. Interestingly still we are going to make use of “Set” but in a smarter way 😎. Code 👇

Problem Statement 7: Find a pair of elements from an array whose sum equals a given number.

Input : Arr = [2,3,5,4,1,7,6,8,9,5,3,3,3,3,3,3,3,3,3], sum = 14
Output : [(8,6),(9,5)] // Array of tuples having sum equal to 14

Solution : Simple solution could be using two “for loops”, but its time complexity turns out to be O(n²), not good enough huh! 🤔 . Can we solve it in O(n) 🤔? Off course we can, “Where there is a will, there is a way 😀”. We are going to use hash 👇

Thanks for reading this🙏🙏. Any feedback in the comments would be appreciated. If you enjoyed reading this post, please share and give some claps👏👏. I will come with 2 new problems and their optimised solution every day.

You can follow me for fresh articles.

--

--