Top 4 algorithms to improve your JavaScript skills

JavaScript is a skill that makes a developer a valuable candidate for any front-end or back-end position. When more than 98% of websites use JavaScript, it is evident that no web development project can take place without JavaScript components. It is required for any interaction between the user and a web page.

Suppose you are building a website to display the score of an ongoing sports tournament. As a developer, you can take two approaches here. First, manually update the value on the server, and users have to refresh the browser screen for score updates. Second, the viewer screen updates automatically every time there is an update in the value on the server. 

Without a doubt, the latter approach is preferable. This is what JavaScript can achieve. It can significantly automate the functionalities and components of a web application.

To truly utilize the functionality of JavaScript, you must master some algorithms. This article will list the top four algorithms a JavaScript developer should know.

1. Linear search

One of the simplest JavaScript algorithms is linear search used for searching a data set. This algorithm starts from the 0th element, comparing the user’s input to return the positional value of the element finally.

It is often used to find missing elements in an array using JavaScript code. Here’s an example:

Find the missing number in this array:

Input: [1, 2, 3, 4, 6, 7, 8, 9, 10]

Algorithm:

const find_missing = function(input) {

  let n = input.length + 1; let sum = 0;

  for (let i in input) {

   sum += input[i];

  }return Math.floor((n * (n + 1)) / 2) – sum;

};

Output: 5

2. Reversal algorithm 

It is the algorithm used in JavaScript to reverse an array. The reversal algorithm creates subarrays and changes them to perform the rotation of an array.

Array alignment is one of the essential JavaScript skills to master. You can achieve the same with the reversal algorithm. Here is an example of a realignment in JavaScript:

Input: [1,2,3]

Code:

const permute = function(nums) {

   let results = [];let go = (current) => {

    if (current.length === nums.length){

     results.push(current);

     return;

    }

    nums.forEach(n => {

     if (!current.includes(n)){

     go([…current, n]);

     }

    });

   }

   go([]);

   return results;

};

Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

The same algorithm can be used for string array alignment.

Here is an example of two input strings that we check for alignment using the reversal algorithm.

Input: s1 = “ab”, s2 = “eidbao”

Output: true

Input: s1 = “aa”, s2 = “eidbao”

Output: false

JavaScript code:

const checkPermutation = function(s1, s2) {

  const len1 = s1.length, len2 = s2.length;

  if (len1 > len2) return false;const count = Array(26).fill(0);

  for (let i = 0; i < len1; i++) {

   count[s1.charCodeAt(i)-97]++;

   count[s2.charCodeAt(i)-97]–;

  }

  if (!count.some(e => e !== 0)) return true;for (let i = len1; i < len2; i++) {

   count[s2.charCodeAt(i)-97]–;

   count[s2.charCodeAt(i-len1)-97]++;

    if (!count.some(e => e !== 0)) return true;

  }

  return false;

};

3. Number-to-word conversion 

This algorithm converts any given number into an English word string. It uses some predefined strings, and the output is generated using the values from these strings.

Input: 786

Output: Seven hundred and eighty-six

JavaScript code:

#include<iostream>

using namespace std;

string getUnit(int n) {

   //Return single digit to word

  string unit[10] = {“Zero”, “One”,”Two”, “Three”,”Four”,”Five”, “Six”,”Seven”,”Eight”,”Nine”};

  return unit[n];

}

string getTwoDigits(int n) {

  //Here n is 2 digit number

  string td[10] = {“Ten”, “Eleven”,”Twelve”,”Thirteen”, “Fourteen”,”Fifteen”,”Sixteen”,”Seventeen”,”Eighteen”,”Nineteen”};

  return td[n%10];

}

string getTenMul(int n) {

  //Here n is a multiple of 10

  string tm[8] = {“Twenty”, “Thirty”,”Fourty”, “Fifty”,”Sixty”, “Seventy”,”Eighty”,”Ninty”};

  return tm[n-2];

}

string getTenPow(int pow) {

  //The power of ten in words

  string power[2] = {“Hundred”, “Thousand”};

  return power[pow-2];

}

void printNumToWord(int n) {

  if(n >= 0 && n < 10)

    cout << getUnit(n) << ” “;   

//Unit values to word

  else if(n >= 10 && n < 20)

    cout << getTwoDigits(n) << ” “;    

//from eleven to nineteen

  else if(n >= 20 && n < 100) {

    cout << getTenMul(n/10)<<” “;

    if(n%10 != 0)

 printNumToWord(n%10); //Recursive call to convert num to word

  }else if(n >= 100 && n < 1000) {

    cout << getUnit(n/100)<<” “;

    cout <<getTenPow(2) << ” “;

if(n%100 != 0) {

     cout << “And “;

printNumToWord(n%100);

    }

}else if(n >= 1000 && n <= 32767) {

   printNumToWord(n/1000);

    cout <<getTenPow(3)<<” “;

    if(n%1000 != 0)

printNumToWord(n%1000);

  }else

printf(“Invalid Input”);

}

main() {

  int number;

  cout << “Enter a number between 0 to 32767: “; cin >> number;

  printNumToWord(number);

}

4. 4sum algorithm 

4sum is another important JavaScript algorithm that finds several uses in computational applications. It is used to find the four elements in an array whose sum equals the required answer.

JavaScript code example:

const fourSum = function(nums, target) {

  let result = [];

  let length = nums.length;

  if (length < 4) return result;

  nums = nums.sort((a, b) => a – b );for (let i = 0; i < length – 3; i++) {

   if (nums[i] === nums[i – 1]) continue;

   for (let j = i + 1; j < length – 2; j++) {

    if (j > i + 1 && nums[j] === nums[j – 1]) continue;let k = j + 1;

    let l = length – 1;while (k < l) {

     const sum = nums[i] + nums[j] + nums[k] + nums[l];if (sum === target) {

     result.push([nums[i], nums[j], nums[k], nums[l]])

     }if (sum <= target) {

      k += 1;

      while (nums[k] === nums[k – 1]) {

       k += 1;

      }

     }if (sum >= target) {

      l -= 1;

      while (nums[l] === nums[l + 1]) {

       l -= 1;

      }

     }

    }

   }

  }return result;

};

Conclusion 

Whether you are a front-end or a back-end developer, these are four important JavaScript algorithms to learn. They are widely used in web applications, from delivery tracking websites to ticket booking apps.

Talent500 has some great learning resources for JavaScript developers. And, if you are looking for job opportunities, sign up here.

 

4 algorithms every developer should learn

Ask any developer, and they will tell you they learned many algorithms as their career progressed. Some algorithms are more important than others. If you are getting started as a developer, you should focus on learning different algorithms to become a proficient programmer. However, with so many algorithms to learn, it can be challenging to pick up the essential developer algorithms.

To help you with the choice, we have created a list of the essential algorithms every developer should learn.

Let’s get started.


1.Dijkstra’s algorithm

Named after one of the most influential computer scientists of all time, Edsger Dijkstra, Dijkstra’s algorithm is used to find the shortest path between two nodes in a graph. It is also known as Dijkstra’s shortest path algorithm.

How does the algorithm work?

Dijkstra’s algorithm is used in computer applications to find the single shortest path in the graph from a source to all graph vertices. It is an iterative algorithm in which a vertex is added to the array with the minimum distance from the source. The iteration is repeated until all the vertices are covered. This is a greedy approach used by the algorithm.

In practical applications, Dijkstra’s algorithm is implemented using a set. It is very efficient when implemented with a Min Heap data structure. It also has a much lower running time at just O(V+ElogV) (V is the total number of vertices, and E is the number of edges in the graph).

Navigation applications like Google Maps use Dijkstra’s algorithm to find the shortest path to reach a destination.

One of the limitations of this algorithm is that it only works with directed and undirected graphs with positive weight edges.

 

2. Merge sort

Sorting algorithms are essential for developers. There are several sorting algorithms, but merge sort is one of the crucial developer algorithms to understand.

How does the algorithm work?

The merge sort algorithm is based on the divide and conquers programming technique that is much more efficient. In a worst-case scenario, this algorithm can sort n number of elements in just O(nlogn) time. For comparison, it is often more efficient than primitive sorting algorithms like the Bubble Sort, which takes O(n^2) time to sort the same number of elements.

The approach here is simple. This algorithm repeatedly breaks down an array into subarrays until each subarray contains only a single element. Then the merge sort recursively merges the subarrays to create a sorted array.

You can learn more about the theoretical aspect of the merge sort algorithm here.

In practical engineering, the merge sort algorithm is used by e-commerce websites to recommend “you may also like” options to the users.

 

3. Depth First Search

Depth First Search or DFS is one of the first developer algorithms taught to computer science students. It is an efficient algorithm to traverse or search a graph and other data structures. DFS can be easily modified to traverse trees.

How does the algorithm work?

The Depth First Search traversal can start from any arbitrary node of the graph, and gradually, it dives into each adjacent vertex until there are no unvisited vertices. The algorithm stops when it encounters a dead-end. It is one of the simplest developer algorithms that you should learn to traverse a data structure easily. The algorithm is also exceptionally efficient, taking only (V+E) time for complete traversal.

In practical applications, the DFS algorithm is used for topological sorting, detecting cycles in the graph, and finding strongly connected components in DNA analysis.

 

4. Minimum spanning tree algorithms

In computer science, a spanning tree is an important concept. A spanning tree is a subset of a graph that has all the vertices covered with the minimum number of edges.

How does this algorithm work?

The minimum spanning tree algorithm (MST) is used to find the minimum cost among a graph’s possible spanning tree. The cost of a graph spanning trees depends on the weight of the edges. There are several MST algorithms, but the two most widely used ones are Kruskal’s and Prim’s.

Kruskal’s algorithm creates a minimum spanning tree for a graph by adding the edge with the minimum cost to a growing set. Here the algorithm first sorts the edges by their weight and then starts adding the edges to the minimum spanning tree. This algorithm is preferred for sorting sparse graphs.

On the contrary, Prim’s Algorithm uses a greedy approach which is ideal for dense graphs. This algorithm creates two sets of structures, one containing the growing minimum spanning tree and the other containing all unused vertices. Each iteration adds the edge with the minimum weight to the graph.

In practical application, MST algorithms are used for broadcast networks, taxonomy, and cluster analysis.

 

Conclusion

Algorithms are the core essentials of computer programming; learning them improves your skill. It is the reason why interviews at tech giants like Google, Amazon, Facebook, and Netflix is focused on evaluating a candidate’s knowledge of algorithms and data structures. Learning algorithms improve your problem-solving skills and as technologies are evolving, more efficient algorithms will be needed to make the most use of these advancements. 

Speaking of learning, Talent500 is an exclusive platform for developers to learn, upskill, and find the best career opportunities. Signup today to connect with mentors and industry experts who can help you land a dream job.