Swifty Challenges #1

Karim Ebrahem
1 min readMar 18, 2018

--

In this series of articles i’ll introduce some interested problems, it’s generic problems you can face them in any situation but i ‘ll solve them using Swift Code, any other solutions in any other Language are welcome :) ❤

Q1: Do two strings have same characters ?!!

There is some cases you need to think of when you gonna attack this question. Firstly, the duplicate chars. Secondly, what is the most efficient way to produce high quality code solving this problem.

sample input:
- ‘abs’ == ‘asb’ , Should return True
- ‘aabbs’ == ‘bsbaa’ , Should return True
- ‘abc’ != ‘Abc’ , Should return False because the problem is Capital Chars

Solution:

let’s make function that take two strings and return true when they have the same characters, and false otherwise.

func isSameCharacters(firstString: String, secondString: String) -> Bool {
var stringToCheck = secondString
for letter in firstString {
if let index = stringToCheck.index(of: letter) {
stringToCheck.remove(at: index)
} else {
return false
}
}
return stringToCheck.count == 0
}

This solution works good, BUT NOT efficient enough. Because of index(of:) is O(n), and remove(at:) is O(n) too.
A more efficient solution, is to make arrays from two strings characters and sort them. Once that done you can do direct comparing for two arrays using ==.

func isSameCharacters(firstString: String, secondString: String) -> Bool {
let arrayFromFirstString = Array(firstString)
let arrayFromSecondString = Array(secondString)
return arrayFromFirstString.sorted() == arrayFromSecondString.sorted()
}

This solution introduce much less code and faster to run ;)

Thanks for now, see you later guys ❤

#Swifty_Challenges_Q1
#Swifty_Challenges

--

--

Karim Ebrahem

Results-oriented iOS software engineer who likes to build things ❤ :)