There are quite a few things that you can learn by solving one computer programming problem in various computer programming languages. So I decided to try out solving Two-Sum problem in 4 languages - C#, JavaScript, Python, and Java.
C#
public int[] TwoSum(int[] nums, int target) {
Dictionary<int, int> dict = new Dictionary<int, int>();
for(int i=0; i < nums.Length; i++){
int searchTerm = target-nums[i];
if(dict.ContainsKey(searchTerm)){
return new int[2] { dict[searchTerm], i};
}else{
dict.Add(nums[i], i);
}
}
return null;
}
JavaScript
var twoSum = function(nums, target) {
const map = {};
for (let i = 0; i < nums.length; i++){
let diff = target - nums[i];
if(map[diff] !== undefined){
return [map[diff], i];
}else{
map[nums[i]] = i;
}
}
return null;
};
Python
def twoSum(self, nums: List[int], target: int) -> List[int]:
map = {}
for i, num in enumerate(nums) :
diff = target - num
if(map.get(diff) != None) :
return [map[diff], i];
else :
map[num] = i;
return None
Java
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
return null;
}
Observations:
1. Code written in Python is probably the most succinct and readable one than the code written in other languages.
2. Coming from a C# background, it was refreshing to note that primary constructs like dictionary, loop, if-else is pretty much same across other programming languages with a difference in syntax. I did have to struggle to find equivalent of Dictionary in Java though.
3. Python and JavaScript are similar in tone. Java and C# are similar in tone. There is a lot less ceremony in Python and JavaScript than what is required in Java and C#.
4. When I ran these solutions in LeetCode, the CPU time and memory consumption for each of the languages was a learning experience.
Runtime: Somehow Java turned out to be the fastest, I am not sure what compile time/run time optimization would cause this (something for me to learn more about). C# was the slowest by an order of magnitude, perhaps due to the extra time required to load assembly, JIT the code etc. Python was much faster than my expectations :).
All of the above observations can also be result of a transient issue on LeetCode servers. So, don't go by the performance numbers right away - better to run these on local machine and make up your mind.