Lenny.is
← All posts

Doing Things the Wrong Way

Why solving problems the brute force way first helps you gain a better understanding before optimizing


Sometimes to do things the right way, you first need to do things the wrong way to better understand the problem and what methodolgies might better apply.

As developers we often learn from complex challenges that we had to do the wrong way because we were not aware of some functions or methods, or standards.

One of my best personal examples is the first time I built a chat app on the web I didn’t know about any frameworks and built it completely using raw javascript and insertHTML. But that helped me gain a great unerstanding of how these things work.

I’ve been taking the same aporach when learning go. I’ve been pracicing on leetcode, something I have never done before. And to all those who are starting off, i cannot reccoment more trying to solve a problem in the most brute force and simple ineffeicent way. to gain a better unerstanding of the problem and then create an optimal solution.

I had a great experience sokving the “Add Two Numbers” probelm where you are given two non-empty linked lists where the digits are stored in reverse order:

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.

Example 2:

Input: l1 = [0], l2 = [0]
Output: [0]

Example 3:

Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */

My initial “wrong” approach was to first navigate throug the list, multiply each number by 10 to the i+1 power to build the correct numbers. and then add both results, and reverse the process to rebuild the reverse linked list.

As I finished my first solution, I then thought, why can’t I just build the final linked list output as I iterate through the individual lists? It was a little hard to wrap my head around, but gave me an amazing opporutnity to learn about pointers in GO, and gain a much better understanding of referencing and de-refrencing.