longest increasing subsequence of a [1 2 .. N] permutation - arrays

Here is the problem:
Given an array of N elements (1 to N), sort the array with one constraint: you can only move an element to begin of the array or end of the array. How many moves do you at least need to sort the array?
For example: 2 5 3 4 1 => 1 2 5 3 4 => 1 2 3 4 5, so I need at least 2 moves.
I figure out one solution: N - length of longest increasing subsequence, in above example the answer if 5 - 3 = 2.
I know a O(NlogN) algorithm to find longest increasing subsequence (LIS). But with elements in the array being in [1, N], I wonder is there a O(N) solution to find LIS of the array?
Or is there a O(N) solution to solve the initial problem given that we know elements are from 1 to N?

What you are looking for is the longest increasing sequence where the difference between any two consecutive elements is 1.
Just finding the longest increasing sequence is not enough, for example with 1 5 3 4 2 the longest inc seq has length 3 but the problem can only be solved in 3 steps not 2 as far as I can tell.
To find the longest inc seq where the difference is 1 in O(N) time and O(N) space can be done by allocating a helper array of size N initialized to all 0 for example. This array will store at position i the length of the longest subsequence up i and if i hasn't been seen yet it will be 0.
Then you go through the unsorted array and when you find an element x you set helper[x] = helper[x-1] + 1 and you update a max variable.
Finally, the cost to sort is input_array.length - max
Example:
array: 3 1 2
0 1 2 3
helper: 0 0 0 0
max = 0
step 1:
check element at position 1 which is 3. helper[3] = helper[3 - 1] + 1 == 1:
0 1 2 3
helper: 0 0 0 1
max = 1
step 2:
check element at position 2 which is 1. helper[1] = helper[1 - 1] + 1 == 1:
0 1 2 3
helper: 0 1 0 1
max = 1
step 3:
check element at position 3 which is 2. helper[2] = helper[2 - 1] + 1 == 2:
0 1 2 3
helper: 0 1 2 1
max = 2
cost = 3 - 2 = 1

Related

Array pattern issue to maintain uniformity

There is an existing array of size 64 that has values 6 values distributed as 0 1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 ...
Please see the image for complete data.
The number of occurrence of 0 in the array is 11 times (at every 6th index), 1 is 11 times ... where as 4 and 5 occurs 10 times each.
There is a necessity to reduce the occurrence of any of these numbers [0 to 5] to a lesser number that could be any number from 0 to 10.
For example, it could be to reduce occurrence of 0 to 6 and 1 to 9.
I am looking for a solid idea to do this. Certainly all the numbers are to be evenly distributed and not something like 0 0 0 0 0 2 2 2 2 2 2 ...
I tried to find the index/position where the reduced value has to filled (64/occurrence of 0 or 2). But at times the index collide with each other and thus is not robust one.
From the example I quoted above, number of occurrence of 0 must be changed to 6 and occurrence of 1 to 9, the result after my algorithm is below -
New location to fill 0 = (Array size)/(new occurrence of 0) = 64/6 = ~10th index
New location to fill 1 = (Array size)/(new occurrence of 1) = 64/9 = ~7 index
For filling 6 0's and 9 1's, first the array is reset after which each of the values are filled to maintain balanced distribution.
After filling 6 0's, the array would be come like this:
Then, after filling 9 1's, the array would be come like this:
The index at 55 already has value 0 and apparently 8th 1 also index to 55 that creates a collision. So I believe, this algorithm to balance the distribution does not work.
How do I populate 6 's, 9 1's and rest of the numbers {2, 3, 4, 5} in the array in a balanced way?

Given an input array, output the minimum number of swaps for sorting the array [duplicate]

This question already has answers here:
Minimum number of swaps needed to change Array 1 to Array 2?
(8 answers)
Closed 7 years ago.
Given an input array I want to calculate the minimum number of swaps to sort the array.
I thought that its equal to inversion count but its not as depicted below:
array [6,4,3]
output: 1, just swap 6 with 3. But the inversions are actually 3.
So given an input array is there an efficient algorithm to determine the minimum number of swaps. I know that selection sort has minimum number of swaps but I also know that it is not efficient.
You can use this method:
Say this is your input array: [4 6 1 8 2 7]
Then, in sorted array, positions of elements will be, respectively: 3 4 1 6 2 5
Create a visit array: [0 0 0 0 0 0]
Start with 1'st index in position array, mark it as visited, jump to the position it represents, until the value of visit in visit[] is set.
Then, once a cycle is complete, chose the next element whose visit value is unset.
For a cycle of k elements, add k-1 to the swap counter.
Step by step in this example will be:
visiting index in position[] visit[]
position[1] = 3 [1 0 0 0 0 0]
position[3] = 1 [1 0 1 0 0 0]
Now, a cycle is formed. Since this cycle has 2 elements, add 1 to swap counter. Now we start with index 2.
position[2] = 4 [1 1 1 0 0 0]
position[4] = 6 [1 1 1 1 0 0]
position[6] = 5 [1 1 1 1 0 1]
position[5] = 2 [1 1 1 1 1 1]
Since visit[2] is set, a cycle is formed. This cycle has 4 elements, so, add 3 to swap counter.
See which next index in visit is still unset. (None). Stop here.
So, your answer is 1 + 3 = 4

How can I get no. of Swap operations to form the 2nd Array

I have got two arrays with same elements... (But in different order)
e.g 1 2 12 9 7 15 22 30
and 1 2 7 12 9 20 15 22
how many swaps operations are needed to form the 2nd array from the first.?
I have tried taking no. of different elements for each index and dividing the result by 2 but that isn't fetching me the right answer...
One classic algorithm seems to be permutation cycles (https://en.m.wikipedia.org/wiki/Cycle_notation#Cycle_notation). The number of swaps needed equals the total number of elements subtracted by the number of cycles.
For example:
1 2 3 4 5
2 5 4 3 1
Start with 1 and follow the cycle:
1 down to 2, 2 down to 5, 5 down to 1.
1 -> 2 -> 5 -> 1
3 -> 4 -> 3
We would need to swap index 1 with 5, then index 5 with 2; as well as index 3 with index 4. Altogether 3 swaps or n - 2. We subtract n by the number of cycles since cycle elements together total n and each cycle represents a swap less than the number of elements in it.
1) re-index elements from 0 to n-1. In your example, arrayA becomes 0..7 and arrayB becomes 0 1 4 2 3 7 5 6.
2) sort the second array using your swapping algorithm and count the number of operations.
A bit naive, but I think you can use recursion as follows (pseudo code):
function count_swaps(arr1, arr2):
unless both arrays contain the same objects return false
if arr1.len <= 1 return 0
else
if arr1[0] == arr2[0] return count_swaps(arr1.tail, arr2.tail)
else
arr2_tail = arr2.tail
i = index_of arr1[0] in arr2_tail
arr2_tail[i] = arr2[0]
return 1+count_swaps(arr1.tail, arr2_tail)
Here's a ruby implementation:
require 'set'
def count_swaps(a1, a2)
raise "Arrays do not have the same objects: #{a1} #{a2}" unless a1.length == a2.length && Set[*a1]==Set[*a2]
return count_swap_rec(a1, a2)
end
def count_swap_rec(a1, a2)
return 0 if a1.length <= 1
return count_swaps(a1[1..-1], a2[1..-1]) if a1[0] == a2[0]
a2_tail = a2[1..-1]
a2_tail[a2_tail.find_index(a1[0])] = a2[0]
return 1 + count_swaps(a1[1..-1], a2_tail)
end

Matlab counting elements in array

Hey guys I just have a quick question regarding counting elements in an array.
the array is something like this
B = [1 0 1 0 0 -1; 1 1 1 0 -1 -1; 0 1 -1 0 0 1]
From this array i want to create an array structure, called column counts and another row counts. I really do want to crate an array structure, even if it is a less efficient process.
basically i want to go through the array and total for each column, row the total amount of times these values occur. For instance for the first row, i want the following output.
Row Counts
-1 0 1
1 3 2
thanks in advance
You can use the hist function to do this.
fprintf('Row counts\n');
disp([-1 0 1])
fprintf('\n')
for row = 1:3
disp(hist(m(i,:),3));
end
yields
Row counts
-1 0 1
1 3 2
2 1 3
1 3 2
I don't fully understand your question, but if you want to count the occurrences of an element in a Matlab array you can do something like:
% Find value 3 in array A
A =[ 1 4 5 3 3 1 2 4 2 3 ];
count = sum( A == 3 )
When comparing A==3 Matlab will fill an array with 0 and 1, meaning the second one that the element in the given position in A has the element you were looking for. So you can count the occurrences by accumulating the values in the array A==3
Edit: you can access the different dimensions like that:
A = [ 1 2 3 4; 1 2 3 4; 1 2 3 4 ]; % 3rows x 4columns matrix
count1 = sum( A(:,1) == 2 ); % count occurrences in the first column
count2 = sum( A(:,3) == 2 ); % ' ' third column
count3 = sum( A(2,:) == 2 ); % ' ' second row
You always access given rows or columns like that.

Longest subsequence with alternating increasing and decreasing values

Given an array , we need to find the length of longest sub-sequence with alternating increasing and decreasing values.
For example , if the array is ,
7 4 8 9 3 5 2 1 then the L = 6 for 7,4,8,3,5,2 or 7,4,9,3,5,1 , etc.
It could also be the case that first we have small then big element.
What could be the most efficient solution for this ? I had a DP solution in mind. And if we were to do it using brute force how would we do it (O(n^3) ?) ?
And it's not a homework problem.
You indeed can use dynamic programming approach here. For sake of simplicity , assume we need to find only the maximal length of such sequence seq (it will be easy to tweak solution to find the sequence itself).
For each index we will store 2 values:
maximal length of alternating sequence ending at that element where last step was increasing (say, incr[i])
maximal length of alternating sequence ending at that element where last step was decreasing (say, decr[i])
also by definition we assume incr[0] = decr[0] = 1
then each incr[i] can be found recursively:
incr[i] = max(decr[j])+1, where j < i and seq[j] < seq[i]
decr[i] = max(incr[j])+1, where j < i and seq[j] > seq[i]
Required length of the sequence will be the maximum value in both arrays, complexity of this approach is O(N*N) and it requires 2N of extra memory (where N is the length of initial sequence)
simple example in c:
int seq[N]; // initial sequence
int incr[N], decr[N];
... // Init sequences, fill incr and decr with 1's as initial values
for (int i = 1; i < N; ++i){
for (int j = 0; j < i; ++j){
if (seq[j] < seq[i])
{
// handle "increasing" step - need to check previous "decreasing" value
if (decr[j]+1 > incr[i]) incr[i] = decr[j] + 1;
}
if (seq[j] > seq[i])
{
if (incr[j]+1 > decr[i]) decr[i] = incr[j] + 1;
}
}
}
... // Now all arrays are filled, iterate over them and find maximum value
How algorithm will work:
step 0 (initial values):
seq = 7 4 8 9 3 5 2 1
incr = 1 1 1 1 1 1 1 1
decr = 1 1 1 1 1 1 1 1
step 1 take value at index 1 ('4') and check previous values. 7 > 4 so we make "decreasing step from index 0 to index 1, new sequence values:
incr = 1 1 1 1 1 1 1 1
decr = 1 2 1 1 1 1 1 1
step 2. take value 8 and iterate over previous value:
7 < 8, make increasing step: incr[2] = MAX(incr[2], decr[0]+1):
incr = 1 1 2 1 1 1 1 1
decr = 1 2 1 1 1 1 1 1
4 < 8, make increasing step: incr[2] = MAX(incr[2], decr[1]+1):
incr = 1 1 3 1 1 1 1 1
decr = 1 2 1 1 1 1 1 1
etc...

Resources