Given two arrays containing array elements and the task is to check if two arrays contain any common elements then it returns True otherwise return False.
Input: array1 = ['a', 'b', 'c', 'd', 'e'] array2 = ['f', 'g', 'c'] Output: true Input: array1 = ['x', 'y', 'w', 'z'] array2 = ['m', 'n', 'k'] Output: false
Method 1: Brute Force approach
- Compare each and every item from the first array to each and every item of second array.
- Loop through array1 and iterate it from beginning to the end.
- Loop through array2 and iterate it from beginning to the end.
- Compare each and every item from array1 to array2 and if it finds any common item then return true otherwise return false.
Time Complexity: O(M * N)
- Create an empty object and loop through first array.
- Check if the elements from the first array exist in the object or not. If it doesn’t exist then assign properties === elements in the array.
- Loop through second array and check if elements in the second array exists on created object.
- If element exist then return true else return false.
Time Complexity: O(M + N)
- Use the inbuilt ES6 function some() to iterate through each and every element of first array and to test the array.
- Use the inbuilt function includes() with second array to check if element exist in the first array or not.
- If element exist then return true else return false
- PHP | Check if two arrays contain same elements
- How to make the cursor to hand when a user hovers over a list item using CSS?
- HTML | DOM item() Method
- HTMLCollection item() Method
- PHP program to add item at the beginning of associative array
- CSSStyleDeclaration item() Method
- How to remove indentation from an unordered list item using CSS?
- How to insert an item at the beginning of an array in PHP ?
- PHP | DOMNamedNodeMap item() function
- PHP | DOMNodeList item() Function
- How to make whole area of a list item in navigation bar is clickable using CSS ?
- How to delete an item or object from the array using ng-click ?
- How to change the background color of the active nav-item?
- How to change the list item bg-color individually using ngFor in Angular 2+ ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.