Problem Statement
You are given a sorted array. However, there is a problem. Someone just rotated the sorted array by K spaces and we do not know the value of K.
Write a program to find the value of K by which the array is rotated. As the array has millions of numbers, it would be good to have a solution which takes minimal time.
Approach to Find the Point of Rotation
Brute Force
Let us try out my favorite approach, the Brute Force Method. It is quite simple, below are the steps:
Start traversing the array from the beginning
There will be a index in the array where the value sto...
Read More
binary search
Understanding Binary Search Algorithm
Introduction
The problem of searching is very trivial. It goes like this:
There is an array of elements A[1..N] and we need to find the index of a given element in the array. In case the element is not present in the array, we can choose to return a specific value (say -1) which suggests that the element doesn't exist in the array.
Binary Search is a very efficient and interesting searching algorithm. Regular searching algorithms take running time proportional to the size of the input. They are called linear time algorithm O(N) to be asymptotically true.
Binary Search on the other ha...
Read More
Find Frequency In Sorted Array
Problem Statement
This is a question from one of the interview experiences. You are given a sorted array of numbers (this can be extended for arrays of characters, strings and what not) and a number K. Find the number of occurrences of K in the array.
Solution
Yes you got that right, it is really very simple. Walk through the array sequentially and if you get K then start counting till you get anything bigger than K. You can break out of the loop after this and the counter will tell you the obvious answer.
So, why am I even writing this post?
Because this is not fun, the above approach te...
Read More