Why I moved from JavaScript to Python for LeetCode
Published: 2024-01-02 18:52:38

Cover image generated using Microsoft Designer.

In December 2023 I started a [YouTube channel](https://www.youtube.com/channel/UCKKsRVUL1QVFi3hDIeaj4Sw) more for the purpose of learning how to tackle coding interview and getting a better understanding of Data Structures and Algorithms. I started the LeetCode 75 study plan and since my strongest language is JavaScript that's what I started to use. After creating about 9 videos and going through more than 70% of the study plan I am ditching JavaScript for Python and here is why.

## Data Structures

A major difference between JavaScript and Python is the built-in data structures. JavaScript has arrays and objects, which are versatile but sometimes inefficient. Python has lists, tuples, sets, and dictionaries, which are more specialized and optimized for different purposes. For example, sets are useful for checking membership and removing duplicates, while dictionaries are useful for mapping keys to values. Python also has some data structures that JavaScript does not have, such as stacks, queues, heaps, and dequeues. These data structures are often needed for solving LeetCode problems, especially those involving graphs, trees, and priority queues. For example, here is how to implement a queue using a list in JavaScript and using a dequeue in Python:


```javascript
// JavaScript
let queue = [];
queue.push(1); // enqueue 1
queue.push(2); // enqueue 2
queue.shift(); // dequeue 1
queue.shift(); // dequeue 2
```

```python
# Python
from collections import deque
queue = deque()
queue.append(1) # enqueue 1
queue.append(2) # enqueue 2
queue.popleft() # dequeue 1
queue.popleft() # dequeue 2
```

As you can see, Python has a built-in dequeue class that supports efficient appending and popping from both ends. JavaScript has to use a list and shift the elements every time a dequeue operation is performed, which is costly in terms of time and space.

## Syntax

I have been using Python professionally for the past 6+ years and JavaScript for probably 10, that being said everytime I move from Python to JavaScript I kind of miss how less code I have to write for Python. JavaScript uses curly braces {} to define code blocks, such as functions, loops, and conditionals. Python uses indentation to define code blocks, which makes the code more readable and concise. For example, here is how a function to check if a number is even looks like in JavaScript and Python:

```javascript
// JavaScript
function isEven(n) {
  if (n % 2 == 0) {
    return true;
  } else {
    return false;
  }
}
```

```python
# Python
def isEven(n):
  if n % 2 == 0:
    return True
  else:
    return False
```

As you can see, Python has less boilerplate code and does not require semicolons or parentheses around the condition. Python also has some syntactic features that JavaScript does not have, such as list comprehensions, multiple assignment, and tuple unpacking. These features can make the code more elegant and expressive. For example, here is how to swap two variables in JavaScript and Python:

```javascript
// JavaScript
let a = 1;
let b = 2;
let temp = a;
a = b;
b = temp;
```

```python
# Python
a = 1
b = 2
a, b = b, a
```

As you can see, Python can swap two variables in one line, while JavaScript needs three lines and a temporary variable. This can save time and space when coding.

Before I piss off the rest of my JavaScript brothers and sisters, newer JS syntax does let us do swapping of values in 1 line as well, but I have not had the most consistent results, especially in the context of LeetCode. If you are using modern JS you can do.

```javascript
let a = 1;
let b = 2;
[a, b] = [b, a];
```

## Libraries

Another difference between JavaScript and Python is their libraries. JavaScript has a standard library that provides some basic functionality, such as math, string, and date operations. However, it does not have many advanced modules or packages that are useful for solving LeetCode problems, such as data structures, algorithms, or testing frameworks. Python has a rich and comprehensive standard library that covers a wide range of topics, such as data structures, algorithms, math, statistics, random, itertools, collections, functools, and unittest. Python also has many third-party libraries that can be easily installed and imported, such as numpy, scipy, pandas, matplotlib, and sklearn. These libraries can provide more functionality and performance for solving LeetCode problems, especially those involving numerical computation, data analysis, or machine learning. For example, here is how to calculate the mean and standard deviation of a list of numbers in JavaScript and Python:

```javascript
// JavaScript
let nums = [1, 2, 3, 4, 5];
let sum = 0;
let sumOfSquares = 0;
for (let num of nums) {
  sum += num;
  sumOfSquares += num * num;
}
let mean = sum / nums.length;
let variance = sumOfSquares / nums.length - mean * mean;
let std = Math.sqrt(variance);
console.log(mean, std);
```

```python
# Python
import numpy as np
nums = [1, 2, 3, 4, 5]
mean = np.mean(nums)
std = np.std(nums)
print(mean, std)
```

As you can see, Python can use the numpy library to calculate the mean and standard deviation of a list of numbers in one line, while JavaScript has to use a loop and some math formulas.

## Video Support

Everytime I get stuck in a problem, which happens more often than I admit, it is as soon as I search for the problem on YouTube the first few that results that come up solve the problem with Python, though it is not super hard to translate the code to JavaScript given that my primary goal is to get a deeper understanding of the Data Structures and Algorithms it felt a bit counter-intuitive to spend the limited time I have translating code, I would rather attach a debugger to the code and step through with different inputs.

## Conclusion

If you follow me on YouTube, LinkedIn and Dev.to expect to see more Python content coming soon :).