Programming Languages war Python, PHP, Javascrip (Nodejs) Two Sum

Hey my friends, a new post about this war. I don't know which is better, but I'll try to figure it out. I hope y'all enjoy this series. Here we go!

This is a challenge of leetcode.com I made this challenge with python3, and next I made PHP and Javacript the same way.

Problem:

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9 Output: [0,1]

Python

I receive the array and the target, I used "for" to iterate the array and I used "enumerate" to get the index, next I subtract the target with the each number in the array. So, I used the method "index" to get the position the result. I check only index after the number that I have, so If I get a second position then I return both positions.

class Solution:
  def twoSum(self, nums, target):
    for index, n in enumerate(nums):
      r = target - n
      try:
        position1 = index
        position2 = nums.index(r, position1 + 1)
        if (position2):
          return [position1, position2]
      except:
        pass
    return []


sol = Solution()
result = sol.twoSum([2,7,11,15], 9)

print(result)

PHP

I receive the array and the target, I used "foreach" to iterate the array and to get the index, next I subtract the target with the each number in the array. So, In PHP exist a method called "array_keys" to get all keys with the result of the rest, this method return an array, then I created some validation to get the result.

<?php
class Solution
{
    public function twoSum($nums, $target)
    {
        foreach ($nums as $i => $n) {
            $r = $target - $n;
            try {
                $position1 = $i;
                $position2 = array_keys($nums, $r);
                if (count($position2) == 1 and $position1 != $position2[0]) {
                    return [$position1, $position2[0]];
                } else if (count($position2) > 1 and $position1 != $position2[0]) {
                    return [$position1, $position2[0]];
                } else if (count($position2) > 1 and $position1 != $position2[1]) {
                    return [$position1, $position2[1]];
                }
            } catch (Exception $e) {

            }

        }
        return [];
    }
}

$sol    = new Solution();
$result = $sol->twoSum([2,7,11,15], 9);

var_dump($result);

?>

Javascript

I receive the array and the target, I used "foreach" to iterate the array and to get the index, next I subtract the target with the each number in the array. So, I used the method "indexOf" to get the position the result. I check only index after the number that I have, so If I get a second position then I return both positions. I used a throw Exception to exit the "foreach" if I have the result.

class Solution {
  twoSum(nums, target) {
    let res = [];
    try {
      nums.forEach((n,i) => {
        const r = target - n;
        const position1 = i;
        const position2 = nums.indexOf(r, position1 + 1);
        if (position1 != -1 && position2 != -1) {
          res = [position1, position2];
          throw BreakException;
        }
      });
    } catch (e) {}

    return res;
  }
}

const sol = new Solution();
const result = sol.twoSum([2,7,11,15], 9);

console.log(result);

Conclusion

  • Structure: Python and Javascript are very similar, change a little for the braces and functions' name, but PHP is different because is not exist a method that you can get the position from a specific position.
  • Lines: Python: 18, PHP: 31, Javascript: 21
  • Time to execution: Python: 48 ms, PHP: 12 ms, Javascript: 76 ms
  • Memory Usage: Python: 14.4 MB, PHP: 15.8 MB, Javascript: 38.8 MB

Would you like that I write about more challenges? Do you think you can do it better?

I hope you enjoy my post and remember that I am just a Dev like you!

Comments (2)

Kevin Pliester's photo

Here in Germany it is unfortunately the case that many web space providers only support PHP and then almost everyone here also uses WordPress. I would so much like to deal more with other things, unfortunately that is not wanted here. Too bad actually.

But I'm glad that PHP performs relatively well! Thanks for your test!

Carlos Rivas's photo

I think PHP is a great language, I think for web is the most important, but In my case I think learn other languages help us to understand better ways to resolve the same bugs.

Thank you for your comment!