The intersection of Two Lines

The intersection of two lines posted in leetcodes did not seem that complex. Based on the title my initial thought was to find an intersecting x and y-axis, fortunately, I was so wrong. It was similar to the most frequent number problem. The question in Leetcode states “Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.” Here are a few examples below.

Attacking the problem.

I started with sorting the two given arrays. The reasoning behind this was based on the question. I was given the ability to return it in any order. Therefore I decided to sort my numbers and find the element that appears x amount of times. Here’s a closer look at my sorting technique below.

Right after sorting the given array I created two variables and set them to zero. Both variables would give me the leverage to start at a particular index in the array and fit into my while loop scheme. Furthermore, I created an empty array to return the elements.

I created a while loop that evaluates to true and goes through both arrays. In addition to the loop, I created a conditional statement that compares both arrays to one another. Once that condition is met I continued to increment through the array. Here’s a better look below.

At the end of my condition, I added an else statement that grabs the frequent element and pushed it to the first array. Furthermore, I continued to increment through both arrays till all elements were found and returned with my empty array.

Thanks for reading.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store