I found a mistake I made in my code associated with indexing an array.
It compiled and I didn't notice the issue for some time. I'm curious what the index really was.
Intended code:
if(arr[i] > 3){//do stuff}
what was written:
if(arr[i > 3]){//do stuff}
what did the array index end up being?
In reality, what happens is very simple.
In the first case, the if checks each element of the array and sees if it is greater than 3.
In the second case, it's more complex than it seems. In practice, as long as the i is greater than 3, the index taken will be 1, as it satisfies the equation x > 3, otherwise I take the index 0.
In practice it is the transformation of the boolean value into an integer value. Once it takes the index, the if does nothing but be true if the value is non-zero, otherwise if the value inside the array is 0 it will be false.
A very practical example for the second problem would be:
int arr[4] = {1,2,3,4};
cout << arr[2 > 4] << endl; //The output would be 1, since 2 > 4 would be false and would return 0 as a result.
Sorry if I made a bad explanation but I tried my best :)
Given an array of elements where every element is repeated except a single element. Moreover all the repeated elements are consecutive to each other.
We need to find out the index of that single element.
Note:
array may not be sorted
expected time O(logn)
range of elements can
be anything.
O(n) is trivial. but how can I figure out logn?
Gave a thought to bitwise operators also but nothing worked out.
Also, I am unable to make use of this statement in this question all the repeated elements are consecutive to each other.
Ex: 2 2 3 3 9 9 1 1 5 6 6
output 5
It can be done in O(logn) by checking if arr[2k] == arr[2k+1], k>=0 - if it is, then the distinct elementt is AFTER 2k+1, if it's not - than it is before before 2k+1.
This allows you to effectively trim half of the array at each step by checking the middle value, and recursing only on a problem half as big, getting it O(logn) overall.
Python code:
def findUnique(arr,l,r):
if r-l < 2:
return (arr[l],l)
mid = (r-l)/2 + l
if mid % 2 != 0:
flag = -1
else:
flag = 0
if (mid == 0 or arr[mid-1] != arr[mid] ) and (mid == len(arr)-1 or arr[mid] != arr[mid+1] ):
return (arr[mid],mid)
if arr[mid+flag] == arr[mid+1+flag]:
return findUnique(arr,mid,r)
return findUnique(arr,l,mid)
Assuming each element is repeated exactly twice, except one, then it is easy.
The first answer is correct, just feel like I could elaborate a bit on it.
So, lets take your example array.
a = [2 2 3 3 9 9 1 1 5 6 6];
If all elements were paired, then you can take an even index and know for sure that the next element will be the same.
a[0] = 2;
a[1] = 2; //as well
a[2] = 3;
a[3] = 3; //as well
General case:
a[k] = a[k+1] = x;
where k is even, and x is some value.
BUT, in your case, we know that there is one index that doesn't follow this rule.
in order to find it, we can use Binary Search (just for reference), with a bit of extra computation in the middle.
We go somewhere in the middle, and grab an element with an even index.
If that elements' value equals to the next elements' value, then your lonely value is in the second part of the array, because the pairing wasn't broken yet.
If those values are not equal, then either your lonely value is in the first half OR you are at it (it is in the middle).
You will need to check couple elements before and after to make sure.
By cutting your array in half with each iteration, you will achieve O(logn) time.
I am new to programming and python. (ref to code below) - I am trying to compare the elements in a list to eliminate duplicates in adjacent numbers in the list (so that all numbers in the resulting list are unique). I actually dont hit the nested "if" statement because this code skips the internal if. However when i try it without the external if, I get an error: File "list2.py", line 22, in remove_adjacent
if nums[i] == nums[i+1]:
TypeError: list indices must be integers, not tuple
def remove_adjacent(nums):
x = len(nums)
print x
for i in enumerate(nums):
if i < x-1:
if nums[i] == nums[i+1]:
del nums[i]
return
It should be for i in range(len(nums)). enumerate returns key/value tuple - which is not integer, as error message says.
To start off this is a homework assignment and I am just looking for some pointers on using recursion.
I have an array of psuedo random integers of size n. I need to sort the array from lowest highest. Below is the recursive sort function that I have created but I know that I am missing a piece but I am not sure what.
template <typename T>
void sort_array_recur(T* random_array,T n)
{
//stop case
if(n = 1 )
{
if(random_array[n] < random_array[ n + 1 ])
{
T temp = random_array[n + 1];
random_array[n] == random_array[n + 1];
random_array[n + 1] == temp;
}
}
else
{
sort_array_recur(random_array, (n - 1));
}
}
I think what I am missing is some sort of insert function that also needs to be called recursively. I have also searched around and nothing seems particular to my situation (or at least I couldn't understand it as such). Thank you for your time in advance.
EDIT:
I guess I forgot to mention the spec says "sort the first n-1 elements of an n-element array. Then place the nth element in its proper position within the n-1 sorted elements". I guess I am not understanding how to sort the first the first n-1 elements of an array?
You are asked to use recursion. Your problem sorts a size n array. The first step is sorting n-1 elements of that array.
Consider m = n-1. Can you apply your problem to a size m array? i.e. sort the first m-1 elements and then place the m'th element in its correct position?
Consider k = m-1. Can you do the same with a size k array?
Do you see how you can use recursion with this problem?
Also consider how you will end the recursion; what will you do with a size 1 array?
Is there a way in linear time by which we can find which is the second largest element of an array ?
Array elements can be positive, negative or zero.
Elements can be repetitive.
No STLs allowed.
Python can be used.
Solution : Sort the array and take the second element but Sorting not allowed
Modification : By definition second largest element will be the one which is numerically smaller. Like if we have
Arr = {5,5,4,3,1}
Then second largest is 4
Addition
Lets say if i want to generalize the question to kth largest and complexity less than linear like nlogn, what can be the solution.
Go through the array, keeping 2 memory slots to record the 2 largest elements seen so far. Return the smaller of the two.
.... is there anything tricky about this question that I can't see?
You can, this is the pseudo algorithm:
max = 2max = SMALLEST_INT_VALUE;
for element in v:
if element > max:
2max = max;
max = element;
else if element > 2max:
2max = element;
2max is the value you are looking for.
The algorithm won't return a correct value for particular cases, such as an array where its elements are equal.
If you want a true O(n) algorithm, and want to find nth largest element in array then you should use quickselect (it's basically quicksort where you throw out the partition that you're not interested in), and the below is a great writeup, with the runtime analysis:
http://pine.cs.yale.edu/pinewiki/QuickSelect
Pseudo code:
int max[2] = { array[0], array[1] }
if(max[1] < max[0]) swap them
for (int i = 2; i < array.length(); i++) {
if(array[i] >= max[0]) max[1] = max[0]; max[0] = array[i]
else if(array[i] >= max[1]) max[1] = array[i];
}
Now, max array contains the max 2 elements.
create a temporary array of size 3,
copy first 3 elements there,
sort the temporary array,
replace the last one in the temporary array with the 4th element from the source array,
sort the temporary array,
replace the last one in the temporary array with the 5th element from the source array,
sort the temporary array,
etc.
Sorting array of size 3 is constant time and you do that once for each element of the source array, hence linear overall time.
Yep. You tagged this as C/C++ but you mentioned you could do it in Python. Anyway, here is the algorithm:
Create the array (obviously).
If the first item is greater than the second item, set first variable to the first item and second variable to second item. Otherwise, do vise-versa.
Loop through all the items (except the first two).
If the item from the array is greater than first variable, set second variable to first variable and first variable to the item. Else if the item is greater than second variable set second variable to the item.
The second variable is your answer.
list = [-1,6,9,2,0,2,8,10,8,-10]
if list[0] > list[1]:
first = list[0]
second = list[1]
else:
first = list[1]
second = list[0]
for i in range(2, len(list)):
if list[i] > first:
first, second = list[i], first
elif list[i] > second:
second = list[i]
print("First:", first)
print("Second:", second)
// assuming that v is the array and length is its length
int m1 = max(v[0], v[1]), m2 = min(v[0], v[1]);
for (int i=2; i<length; i++) {
if (likely(m2 >= v[i]))
continue;
if (unlikely(m1 < v[i]))
m2 = m1, m1 = v[i];
else
m2 = v[i];
}
The result you need is in m2 (likely and unlikely are macros defined as here for performance purposes, you can simply remove them if you don't need them).
I think the other answers have not accounted for the fact that in an array like [0, 1, 1], the second largest is 0 (according to the updated problem definition). Furthermore, all mentions of quickselect are not O(n) but rather O(n^2) and are doing much more work than necessary (on top of which that is a sorting algorithm which the problem statement disallowed). Here is a very similar algorithm to Simone's but updated to return the second largest unique element:
def find_second(numbers):
top = numbers[0]
second = None
for num in numbers[1:]:
if second is None:
if num < top: second = num
elif num > top:
second = top
top = num
else:
if num > second:
if num > top:
second = top
top = num
elif num < top: second = num
if second is not None: return second
return top
if __name__ == '__main__':
print "The second largest is %d" % find_second([1,2,3,4,4,5,5])
// Second larger element and its position(s)
int[] tab = { 12, 1, 21, 12, 8, 8, 1 };
int[] tmp = Arrays.copyOf(tab, tab.length);
int secMax = 0;
Arrays.sort(tmp);
secMax = tmp[tmp.length - 2];
System.out.println(secMax);
List<Integer> positions = new ArrayList<>();
for (int i = 0; i < tab.length; i++) {
if (tab[i] == secMax) {
positions.add(i);
}
}
System.out.println(positions);