Coding Test Question 1

Question: Given 2 arrays, create a function that lets a user know (true/false) whether these two arrays contain any common items

Definition:

  • Input: 2 arrays
  • Output: boolean

Clarification: Is time complexity is most important?

Brute Force approach: Nested loop.(Comparing every element.) — This yields time complexity of O(a * b) and space complexity of O(1). Not ideal.

const array1 = ['a', 'b', 'c', 'x'];
const array2 = ['y', 'b', 'z'];

Better approach: Assign a key-value pair by looping through first array. Check for same value while looping through second array. — Time complexity: O(a+b), Space Complexity: O(a).

const array1 = ['a', 'b', 'c', 'x'];
const array2 = ['y', 'b', 'z'];

First(Brute force) approach will yield 4*3 times of for loop(will disregard other minor executions) while Second approach will yield 4+3 times of for loop. As the input increases, the results between first and second approach will differ drastically.