웹개발/코딩 테스트 문제 & 풀이

[코딩문제] Create a function that let's a user know (true/false) whether these two arrays contain any common items

데브리 2022. 2. 1. 14:46

 

문제. 두 arrays에서 공통되는 아이템이 있다면 true, 없다면 false를 도출하는 function 만들기

 

 
const array1 = ['a', 'b', 'c', 'd'];
const array2 = ['d', 'f', 'b'];            // 이 경우 'b'가 공통되기 때문에 true가 나와야 함.
 

 

 

1. for loop을 두개나 써서 결과가 도출되기 까지 시간이 소요되는 답안 (바람직x)

function containsCommonItem(arr1, arr2) {
  for (let i = 0; i < arr1.length; i++) {
    for (let j = 0; j < arr2.length; j++) {
      if (arr1[i] === arr2[j]) {
        return true;
      }
    }
  }
  return false;
}

//0(a*b)

 

 

 

 

 

 

 

2. better 답안

function containCommonItem2(arr1, arr2) {
  //loop through first array and create object where properties === items in the array
  let map = {};
  for (let i = 0; i < arr1.length; i++) {
    if (!map[arr1[i]]) {
      const item = arr1[i];
      map[item] = true;
    }
  }

  // loop through second array and check if item in second array exists on created object.
  for (let j = 0; j < arr2.length; j++) {
    if (map[array[j]]) {
      return true;
    }
  }
  return false;
}

 

 

 

 

 

 

 

3. sum과 has를 쓴 Best 답안

function containCommonItem3(arr, sum) {
  const mySet = new Set();
  const len = arr.length;
  for (let i = 0; i < len; i++) {
    if (mySet.has(arr[i])) {
      return true;
    }
    mySet.add(sum - arr[i]);
  }
  return false;
}

containCommonItem3([1, 2, 3], 2);

 

 

 

반응형

 

 

 

 

 

*출처: Master the Coding Interview: Data Structures + Algorithms by Andrei Neagoie