Big O notation is probably the bane of many Computer Science undergrads’ existence. It most certainly was one of mine back in my college days. When you are young and learning programming for the first time, why would you want to waste your time on boring lectures learning about algorithm theories and optimization?
When you are a student, you wanted to get in front of a computer and start coding! You felt that it did not really matter how you went about coding up a project. As long as it compiled and provided the expected output, you marked it as a success.
I did not understand that Big O notation and those advanced algorithms were actually going to be needed until I entered the job market. They became very important to me during my technical interviews with potential employers. In a world of emerging technologies and multiple programming languages, those lectures and core concepts from your Computer Science classes are a common language we all can speak.
I remember having a technical interview at Amazon about a month before I got into Salesforce. I was in their office in Seattle and working out a programming problem on a white board in one of their conference rooms. I forget what the question was, but I was struggling to find a solution to it that did not involve using a nested for loop.
“Can you do any processing of the data before entering the for loop?” the interviewer suggested.
I thought about this some more and came up with a solution that involved creating another for loop before entering my original loop. But this did not seem right to me. The whole point was that I was trying to avoid looping through all the data a second time, right?
When I expressed my doubts to the interviewer, he asked, “What’s the Big O notation of your solution?”
Well, one loop is going to be n, the second loop is going to be n, so together they will be 2n…
… and you drop the leading 2 from n, so it’s O(n). It’s linear!
“Right,” the interviewer said with a smile. “And linear is a perfectly acceptable solution.”
I obviously did not land that job, otherwise I would have never gotten into Salesforce in the first place. But that realization that multiple for loops still yield an acceptable solution became o core philosophy of mine when it comes to Salesforce development in Apex.