Which Way Am I Sorting?

I always got confused as to what’s the end result my sort. I wasn’t sure if it would end up being ascending or descending. The ultimate trick is to not think of up vs down. Instead think of increasing/decreasing from left to right. We perceive arrays as horizontal beings. Hence left and right make more sense vs up and down let nums = [1,4,2,3] let sorted_nums = arr.sorted(by: { $0 < $1 // left is smaller [1,2,3,4] i....

August 3, 2022 · 2 min

Recover Binary Tree

Question: You have a binary tree. But only two of its elements have been swapped. This makes it a faulty binary tree. The challenge is to swap those two elements. And fix the tree. Solution I knew I had to traverse it. But then what? With a little help from reading online, I realized I should traverse it, and store the values into an array. Then you just loop the array and find the bad indexes....

June 27, 2022 · 4 min

How to Calculate the Middle Index?

A good number of interview questions require you to constantly split an array/string in half. This is relatively easy to achieve when the array count is odd. However when the count is even, it’s not as easy. let a = [1,3,8,10,22] // middle index is 2 let b = [1,3,8,10] // middle index is 1.5 which is non-existent. So what now? Most important thing to note is: There’s no such thing as “middle index” when the count is even, I mean there’s two middles in that case....

June 19, 2022 · 4 min