Algorithm gymnastics 4

Find the Smallest Common Number From the three integer arrays sorted in ascending order, we need to find the smallest number that is common to all three arrays.

Description

Given three integer arrays sorted in ** ascending order **, implement an algorithm to find the smallest number common to all three arrays.

Let's look at the following three arrays. The solution is ** 6 **, the minimum number common to all arrays. Screen Shot 2019-12-17 at 19.16.20.png

Screen Shot 2019-12-17 at 19.16.39.png Screen Shot 2019-12-17 at 19.16.53.png

Tips

  1. Take advantage of ascending arrays.
  2. Use three pointers.

Solution Runtime Complexity O(n)

Memory Complexity O(1)

Commentary

Consider how to take advantage of the fact that arrays are sorted in ascending order.

Scan each array using three iterators at the same time. You can start by scanning the array from the 0th index, which has the minimum value for each array.

If the values of the array indexes pointed to by the three iterators are equal, Since it is the minimum value that exists in all arrays (because the arrays are sorted in ascending order), that value is returned.

Otherwise, check the iterator that points to the smallest of the three points Increment the iterator to point to the next index.

Returns Null if no common number is found when any of the three iterators reach the end of the array.

Implementation

Screen Shot 2019-12-17 at 19.51.02.png

Test Screen Shot 2019-12-17 at 19.46.59.png

Output Screen Shot 2019-12-17 at 19.47.47.png

Recommended Posts

Algorithm gymnastics 12
Algorithm gymnastics 10
Algorithm gymnastics 3
Algorithm gymnastics 9
Algorithm gymnastics 14
Algorithm Gymnastics 15
Algorithm Gymnastics 16
Algorithm gymnastics 8
Algorithm Gymnastics 17
Algorithm Gymnastics 18
Algorithm gymnastics 11
Algorithm gymnastics 5
Algorithm gymnastics 4
Algorithm Gymnastics 24 Subsets
Algorithm Gymnastics 23 Merge Intervals
Algorithm Gymnastics 20 Remove Duplicates
Algorithm Gymnastics 21 LinkedList Cycle
Algorithm Gymnastics 24 Cyclic Sort
Algorithm Gymnastics 19 No-repeat Substring
Algorithm exercise 6
Algorithm Gymnastics 24 Reverse a Linked List
Python algorithm
Algorithm Gymnastics 20 Pair with Target Sum
Algorithm Gymnastics 22 Squaring a Sorted Array
Algorithm Gymnastics 24 Middle of the Linked List
Python memorandum (algorithm)
Dictionary learning algorithm
String search algorithm