It is an interesting puzzle I came across , according to which , given an array , we need to find the ninja index in it.
A Ninja index is defined by these rules :
An index K such that all elements with smaller indexes have values lower or equal to A[K] and all elements with greater indexes have values greater or equal to A[K].
For example , consider :
A[0]=4, A[1]=2, A[2]=2, A[3]=3, A[4]=1, A[5]=4, A[6]=7, A[7]=8, A[8]=6, A[9]=9.
In this case, 5
is a ninja index , since A[r]<=A[5] for r = [0,k] and A[5]<=A[r] r = [k,n].
What algorithm shall we follow to find it in O(n) . I already have a brute force O(n^2) solution.
EDIT : There can be more than 1 ninja index , but we need to find the first one preferably. And in case there is no NI , then we shall return -1.
To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.
The index indicates the position of the element within the array (starting from 1) and is either a number or a field containing a number.
We can use bitwise AND to find the unique element in O(n) time and constant extra space. Create an array count[] of size equal to number of bits in binary representations of numbers. Fill count array such that count[i] stores count of array elements with i-th bit set. Form result using count array.
An array is an ordered list of values that you refer to with a name and an index. For example, consider an array called emp , which contains employees' names indexed by their numerical employee number. So emp[0] would be employee number zero, emp[1] employee number one, and so on.
Precompute minimum values for all the suffixes of the array and maximum values for all prefixes. With this data every element can be checked for Ninja in O(1).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With