Understanding Other People's Solutions Are One Of The Most Valuable Lessons
This week I have been solving a lot of algorithms questions on binarysearch.com as usual. I found this one problem is easy, if only you truly understand the problem first and not over complicated. Anyway, here is the question:
Understand the problem
First, let’s try to understand the question. The question is giving n people and a list of groups(pairs) of people, means as long as you are in the same array with that other person, you guys are friends with one another.
Solution
So the way I solved the problem is to create a hash table to check if the first person in the array and the second person in the same array are unique(they are not the same person). If they both are different people, that means they both are friends with one another. If that is true, we push them into the new array (arr). Lastly, we want to check whether the new array (arr) length is equal to the n people in the list; if this is true, everyone has at least one friend.
Although I quickly solved the question, I realized some tricks I never knew before seeing other people's solutions. My whole code basically can compute to just this one-liner code:
I never knew the .flat() method in JavaScript; it essentially flattens the array, which is to reduce the nesting of an array (more information about .flat()). The .flat() method is relatively new for me; it was introduced in ES2019 and heavily used in Javascript’s functional programming paradigm.
Also, It is always good to learn to check people’s solutions and see different approaches. For instance, someone uses the .set() method to solve the problem, which is the right data structure for this type of situation:
Since the .set() method meant storing unique values, I think this is a better solution than the previous two. If you can console.log(map), it is an obvious explanation itself:
Another thing I didn’t know before, but I do know now is that I didn’t know we can use array type inside the for…of loop like that( let [a,b] of friends), maybe I am just not familiar enough with for …of loop.
Summary
One valuable lesson I learned from solving easy problems is that although you solved it fast and quickly, don’t move on to the next question just yet. See if there is an alternative way (better solution, faster time/space complexity, different approaches, etc.) of solving the problem. It is always good to expand your knowledge, whether with different methods, approaches, and techniques. Sometimes you may never know you learn something valuable from other people’s solutions. Without seeing other people’s answers, I would not think I will ever learn .flat() anytime soon.