Leetcode tricks in Swift

Tom Zurkan
3 min readDec 18, 2020

It’s time for another article. This time I am going to talk about a really fun puzzle game I’m sure we have all played. Leetcode. Now, I have no affiliation with Leetcode. But, I really love the programmer puzzles that this site provides. It might seem like a time sink, but, I feel like it sharpens your skills a little while also giving you a fun brain teaser. It’s also great preparation for interviewing.

I chose to use Swift as my Leetcode challenge language because I enjoy the language. I think it is succinct and graceful programmatically. It’s fun using swift but there are a couple of things that can be a little bit of a gotcha. I thought I might cover a couple of things that I quickly adopted. The examples and approach I am mentioning below illustrate my point perfectly.

Let’s say you are given a string and you are to return all permutations of that string. If you are going to take that string and construct new strings using ranges, advance by indexes or insert(at:), it is going to get messy pretty fast. If you have to provide all of the extensions you want, it will also seem like too much effort. Lastly, inserting in a string is inefficient.

Below is how I would tackle something like this. It does increase your memory footprint but it is also tighter and more readable code.

Example:

Give all permutations of String

e.g. “123” returns [“123”, “132” , “213”, “231”,”312", “321”]

So, If you implemented this using a string it would be somewhat cumbersome. Below is an example implementation of backtracking by mapping the string to a string array and then using that along with reduce to get the permutations.

class Solution {  var sol = [String]()  func permutations(s:String) -> [String]    let ss = s.map({String($0)})    getPerms(ss, 0)    return sol  }  private func getPerms(_ s:[String],_ index:Int) {    if index == s.count {      sol.append(s.reduce(“”, +))      return    }    var i = index    while i < s.count {      var st = s      st.swapAt(index, i)      getPerms(st, index + 1)      st.swapAt(index, i)      i = i + 1    }  }}

Above, we use backtracking which might not be the most efficient approach O(n*n!). But, you can see how easy it is to manipulate the string array and then turn that back into a string.

I keep using these tricks again and again in Leetcode. One thing you might notice here is that I use the while loop and then increment i instead of a for loop. That seems to be the best approach more times than not as well. Here’s another quick example:

class Solution {  func reverseWords(_ s: String) -> String {
let ss = s.map({String($0)})
var words = [String]()
var word = [String]()
var i = 0 while i < ss.count {
if ss[i] == “ “ {
if word.count > 0 {
words.append(word.reduce(“”, +))
word.removeAll()
}
}
else {
word.append(ss[i])
} i = i + 1 } if word.count > 0 { words.append(word.reduce(“”, +)) word.removeAll() } words.reverse() return words.joined(separator:” “) }}

Lastly, I will also use a if != nil and then ! inside the if statement instead of binding to a new variable. It just seems more efficient in Leetcode. If it was shipping code I would bind. Some people might disagree with these “short cuts” for Leetcode. But, since I’ve done about 50 medium difficulty problems over the last few weeks, it has proven to be the most efficient way in Swift (time footprint usually blows away others. Memory, better than some…).

So, now I’ve told you a few of my tricks when using swift in Leetcode. If you haven’t had a chance to play around there, do yourself a favor and play around. For me it is my Sunday crosswords type thing. I hope that this helps others. However, I may now go down in my ranking since I let the cat out the bag. :D Happy Coding!

--

--

Tom Zurkan

Engineer working on full stack. His interests lie in modern languages and how best to develop elegant crash proof code.