Find Top K Frequent Elements |3 Approaches

Find top k frequent elements in an array of integers. Let’s first understand the problem statement and the we will solve this problem using multiple approaches.

Given a non-empty array of integers, return the k most frequent elements.

Example 1:

Input: arr = {3, 4, 4, 4, 7, 7}, k = 2

Output: {4, 7}

Two most frequent elements are 4 and 7.

Example 2:

Input: arr = {3}, k = 1

Output: {3}

NOTE:

* k is always valid, 1 ≤ k ≤ number of unique elements.

* The time complexity must be better than O(nlogn), where n is the array’s size.

* It’s guaranteed that the answer is unique, in other words, the set of the top k frequent elements is unique.

* Answer can be returned in any order.

Search in Rotated Sorted Array

Write a code to search in rotated sorted array.

Given a sorted array and a target value.  Suppose this sorted array is rotated any number of times.

Write a code to search a target value in a sorted and rotated array. Return the index of a target value. If the target value is not found then return -1.

NOTE: The array only contains distinct values.

For example:

Input: {4, 5, 6, 7, -1, 0, 1, 2},  target = 0

Output: 5

In the above example, we have to search 0 in the rotated array. The element 0 is present at 5th index.

Find the Intersection of Two Linked Lists

In this tutorial, i am going to explain how to find the intersection of two linked lists. 

Given the heads of two singly linked lists. We have to write a code to find the intersection point of two linked lists. If no intersection point is found then return null.

You may assume there are no cycles anywhere in the entire linked structure. We have to solve this problem in O(n) time complexity and by using O(1) space.

For example:

Linked list 1:  4 -> 6 -> 2 -> 7 -> NULL

Linked list 2: 8 -> 2-> 7 -> NULL

In this example, the intersection point of two lists is at node 2.