Member-only story

How to write an algorithm to find the shortest distance between two elements of an array in Swift

Alcivanio (Swift)
4 min readFeb 7, 2020

--

Today I was presented to this problem. Basically given a list of elements, I’d have to find the nearest distance between two elements of that list.

You can see an example of given list. Notice that we’re not talking about a set, which means that elements could possibly repeat.

Let’s go through some possible situations and answers for these situations.

Ok so let’s go to the algorithm. First of all we’re going to create a class wrapper to contain our information. We can call it NearestIndexFinder. The initializer of this class will receive the array of elements. Here’s where our algorithm will start working. But before let’s think a little about the problem.

--

--

Alcivanio (Swift)
Alcivanio (Swift)

Written by Alcivanio (Swift)

Computer Engineer + iOS Engineer. I am interested in Swift, Kotlin, Firebase, Data Structures, ASO & On Solving Real World Problems.

No responses yet

Write a response