check if two arrays are the same in constant time in javascript

To check if two arrays are the same in constant time, we can use a simple trick. We can compare the length of the two arrays first, if they are not equal, then we can conclude that the two arrays are not the same. If the lengths are the same, we can use the Array.prototype.reduce method to compare each element of the two arrays.

Here is the code snippet:

index.tsx
function areArraysEqual(a, b) {
  if (a.length !== b.length) {
    return false;
  }

  return a.reduce((acc, val, i) => {
    return acc && val === b[i];
  }, true);
}
169 chars
10 lines

In the code above, we first compare the length of the two arrays a and b. If they are not equal, we return false, indicating that the arrays are not the same. If they are equal, we use reduce to iterate over both arrays, element by element, and compare each pair of elements.

If any pair of elements is not equal, we will return false to indicate that the arrays are not the same. If all pairs of elements are equal, we will return true to indicate that the arrays are the same.

This approach has a constant time complexity of O(n), where n is the length of the arrays.

gistlibby LogSnag