Related
I'm trying to merge/multiply duplicate longs in an array recursively.
So if I have something like that:
long[] arr = {3, 5, 6, 6, 7} => long[] arr = {3, 5, 36, 7}
That's what I've got:
public static long[] merge(long[] ns, int i, Merger m) {
m.merge();
if(i > ns.length) return new long[0];
if(i < 0) return merge(ns, 0, m);
else {
if(ns[i] != ns[i+1]) {
return append(merge(ns, i-1, m), ns[i+1]);
}
else {
return append(merge(ns, i-1, m), ns[i] * ns[i+1]);
}
}
public long[] append(long[] old, long newLast) {
long[] result = Arrays.copyOf(old, old.length + 1);
result[old.length] = newLast;
return result;
}
}
But it stucks in its recursion.
There are multiple cases that are not clear from the approach that you've taken.
What happens when there are multiple instances of the same value? Do they simply get multiplied? In your current logic, you check whether ns[i] != ns[i+1], which assumes that a. the list if sorted, .b. that occurrences come up only in pairs.
To see why (a) holds, your current approach would not multiply the two 6s if your input list were [3,6,5,6,7]. Is this a valid assumption to make?
To see why (b) holds, assume you had for input [1,3,5,6,6,6,7]. In this case, on multiplying the first two occurrences of 6, your resultant list would be [1,3,5,36,6,7], and your current logic would not end up multiplying 36 and 6.
Is this intended?
Before implementing a recursive solution, it would be instructional to write out the iterative implementation first. That way, the problem specification will become clearer to you.
Assuming these two assumptions hold for the specific problem you're trying to solve, the implementation below works.
(Note - this is implemented in Python. if you're looking for a Java specific solution, you should modify your question specifying it + add a Java tag to your post. Someone fluent in Java can then help you out. This solution tries to resemble your approach as closely as possible.)
def merge(ns, i, resultant_list = None):
if resultant_list is None:
resultant_list = []
if i > len(ns)-1:
return resultant_list
else:
if i == len(ns)-1:
append(resultant_list, ns[i])
return resultant_list
elif(ns[i] != ns[i+1]):
append(resultant_list, ns[i])
return merge(ns, i+1, resultant_list)
else:
append(resultant_list, ns[i] * ns[i+1])
return merge(ns, i+2, resultant_list)
def append(old, newLast):
old.append(newLast)
return old
I need to write a function which returns the intersection (AND condition) of all the arrays generated in every iteration for an array of queries.
If my query is given by: query[] = {"num>20", "avg==5", "deviation != 0.5"} then, n runs from 0 to length of query. The query is passed on to a function (get_sample_ids) which compares the condition against a list of samples possessing certain information. The returned array numbers from get_sample_ids are the index of the respective samples.
query[] = {"num>20", "avg==5", "deviation != 0.5"}
int intersected_array*;
for n=0:query.length-1
int arr* = get_sample_ids(query[n]);
// n=0: [1, 7, 4, 2, 6]
// n=1: [3, 6, 2]
// n=2: [6, 2]
end;
Expected output: intersected_array* = [6, 2]
I've coded an implementation which has 2 arrays (arr*, temp*). For every array returned in the iteration, it is first stored in the temp* array and the intersection of arr* and temp* is stored in arr*. Is this an optimal solution or what is the best approach?
This is quite efficient but could be tiresome to implement (haven't tried it).
Determine the shortest array. Benefit of using C is that if you don't know their length, you can use the pointers to arrays to determine it if they are placed sequentially in memory.
Make a <entry,boolean> hash map for the entries in shortest. We know the size and if anything it's only going down in next steps.
Iterate through an array. Start by initiating the whole map to false. For each entry check it in map.
Iterate through map deleting all the entries that weren't checked. Set all the values to false.
If there any new arrays left go back to step 3. with a new array.
The result are the keys in the final map.
It looks like much but we didn't have to resort to any high complexity measures. Key to good performance is using hash map because of constant access time.
Alternatively:
Make the map be <entry,int>. This way you can count up all the recurrences and don't have to reset it at every iteration, which adds to complexity.
At the end just compare the number of array's to the the values in map. Those that match are your solution.
Complexity:
Seems like O(n).
First I would sort the arrays in ascending order more easy to preform tasks
you could also zero pad the arrays so all the arrays shall be in the same size
[1, 2, 0, 4, 0, 0, 6, 7]
[0, 2, 3, 4, 0, 0, 6, 7]
[0, 2, 0, 0, 0, 0, 6, 0]
like a matrix so you could easily find the intersection
all this shall take a lot of PC run time
enjoy
Here is Jquery implementation of #ZbyszekKr solution -
I have $indexes as array of arrays for all characters in English alphabets which stores which char is present in which rows. $chars is the array of char string I am trying to filter in my HTML table rows. Below method is a part of larger scheme in filtering rows as a user types, when there are more than say 5000 rows in your table.
PS - There are some obvious redundancies, but those are necessary for my plugin I am making.
function intersection($indexes, $chars){
map = {};
$minLength = Number.MAX_SAFE_INTEGER; $minIdx = 0;
//get shortest array
$.each($chars, function(key, c){
$index = getDiffInNum(c, $initialChar);
$len = $indexes[$index].rows.length;
if($len < $minLength){
$minLength = $len;
$minIdx = $index;
}
});
//put that array values in map
$minCount = 1;
$.each($indexes[$minIdx].rows, function(key, val){
map[val] = $minCount;
});
//iterate through other arrays to figure out count of element
$.each($chars, function(key, c){
$index = getDiffInNum(c, $initialChar);
if($index != $minIdx){
$array = $indexes[$index].rows;
$.each($array, function(key, val){
if(val in map){
map[val] = map[val] + 1;
}
});
$.each(map, function(key, val){
if(val == $minCount){
delete map[key];
}
});
$minCount++;
}
});
//get the elements which belong in intersection
$intersect = new Array();
$.each(map, function(key, val){
if(val == $chars.length){
$intersect.push(parseInt(key));
}
});
return $intersect;
}
Is there a standard way to copy an array excluding elements equal to an object? My current naive solution:
T[] without(T)(T[] array, T what){
T[] a;
foreach(element; array)
if(element != what)
a ~= element;
return a;
}
Removing elements from an array seems unnecessarily difficult in D and the immutable approach seems pretty nice, so I'd like to create a new one instead of modifying the existing array.
std.array.replace would work well, but it does not accept [] as second argument.
It sounds like you want std.algorithm's filter.
For example:
import std.algorithm, std.array;
void main() {
auto a = [1, 2, 3, 3, 4];
auto without3 = a.filter!(x => x != 3).array;
assert(without3 == [1, 2, 4]);
}
note that filter returns a FilterResult (a type of range), not an array. The call .array at the end (from std.array) converts the FilterResult into an array.
You should call .array if you want to create and store a separate 'copy'. If you just want to iterate over the FilterResult, you can use foreach like you would with any range.
Given two integer arrays of size N, design an algorithm to determine whether one is a permutation of the other. That is, do they contain exactly the same entries but, possibly, in a different order.
I can think of two ways:
Sort them and compare : O(N.log N + N)
Check if the array have same number of integers and the sum of these integers is same, then XOR both the arrays and see if the result is 0. This is O(N). I am not sure if this method will eliminate false positives completely. Thoughts. Better algorithms?
Check if the array have same number of integers and the sum of these integers is same, then XOR both the arrays and see if the result is 0.
This doesn't work. Example:
a = [1,6] length(a) = 2, sum(a) = 7, xor(a) = 7
b = [3,4] length(b) = 2, sum(b) = 7, xor(b) = 7
Others have already suggested HashMap for an O(n) solution.
Here's an O(n) solution in C# using a Dictionary<T, int>:
bool IsPermutation<T>(IList<T> values1, IList<T> values2)
{
if (values1.Count != values2.Count)
{
return false;
}
Dictionary<T, int> counts = new Dictionary<T, int>();
foreach (T t in values1)
{
int count;
counts.TryGetValue(t, out count);
counts[t] = count + 1;
}
foreach (T t in values2)
{
int count;
if (!counts.TryGetValue(t, out count) || count == 0)
{
return false;
}
counts[t] = count - 1;
}
return true;
}
In Python you could use the Counter class:
>>> a = [1, 4, 9, 4, 6]
>>> b = [4, 6, 1, 4, 9]
>>> c = [4, 1, 9, 1, 6]
>>> d = [1, 4, 6, 9, 4]
>>> from collections import Counter
>>> Counter(a) == Counter(b)
True
>>> Counter(c) == Counter(d)
False
The best solution is probably a counting one using a map whose keys are the values in your two arrays.
Go through one array creating/incrementing the appropriate map location and go through the other one creating/decrementing the appropriate map location.
If the resulting map consists entirely of zeros, your arrays are equal.
This is O(N), and I don't think you can do better.
I suspect this is approximately what Mark Byers was going for in his answer.
If a space complexity of O(n) is not a problem, you can do it in O(n), by first storing in a hash map the number of occurrences for each value in the first array, and then running a second pass on the second array and check that every element exists in the map, decrementing the number the occurrences for each element.
Sort the contents of both arrays numerically, and then compare each nth item.
You could also take each item in array1, and then check if it is present in array2. Keep a count of how many matches you find. At the end, the number of matches should equal the length of the arrays.
i have an array which might contain duplicate elements(more than two duplicates of an element). I wonder if it's possible to find and remove the duplicates in the array:
without using Hash Table (strict requirement)
without using a temporary secondary array. No restrictions on complexity.
P.S: This is not Home work question
Was asked to my friend in yahoo technical interview
Sort the source array. Find consecutive elements that are equal. (I.e. what std::unique does in C++ land). Total complexity is N lg N, or merely N if the input is already sorted.
To remove duplicates, you can copy elements from later in the array over elements earlier in the array also in linear time. Simply keep a pointer to the new logical end of the container, and copy the next distinct element to that new logical end at each step. (Again, exactly like std::unique does (In fact, why not just download an implementation of std::unique and do exactly what it does? :P))
O(NlogN) : Sort and replace consecutive same element with one copy.
O(N2) : Run nested loop to compare each element with the remaining elements in the array, if duplicate found, swap the duplicate with the element at the end of the array and decrease the array size by 1.
No restrictions on complexity.
So this is a piece of cake.
// A[1], A[2], A[3], ... A[i], ... A[n]
// O(n^2)
for(i=2; i<=n; i++)
{
duplicate = false;
for(j=1; j<i; j++)
if(A[i] == A[j])
{duplicate = true; break;}
if(duplicate)
{
// "remove" A[i] by moving all elements from its left over it
for(j=i; j<n; j++)
A[j] = A[j+1];
n--;
}
}
In-place duplicate removal that preserves the existing order of the list, in quadratic time:
for (var i = 0; i < list.length; i++) {
for (var j = i + 1; j < list.length;) {
if (list[i] == list[j]) {
list.splice(j, 1);
} else {
j++;
}
}
}
The trick is to start the inner loop on i + 1 and not increment the inner counter when you remove an element.
The code is JavaScript, splice(x, 1) removes the element at x.
If order preservation isn't an issue, then you can do it quicker:
list.sort();
for (var i = 1; i < list.length;) {
if (list[i] == list[i - 1]) {
list.splice(i, 1);
} else {
i++;
}
}
Which is linear, unless you count the sort, which you should, so it's of the order of the sort -- in most cases n × log(n).
In functional languages you can combine sorting and unicification (is that a real word?) in one pass.
Let's take the standard quick sort algorithm:
- Take the first element of the input (x) and the remaining elements (xs)
- Make two new lists
- left: all elements in xs smaller than or equal to x
- right: all elements in xs larger than x
- apply quick sort on the left and right lists
- return the concatenation of the left list, x, and the right list
- P.S. quick sort on an empty list is an empty list (don't forget base case!)
If you want only unique entries, replace
left: all elements in xs smaller than or equal to x
with
left: all elements in xs smaller than x
This is a one-pass O(n log n) algorithm.
Example implementation in F#:
let rec qsort = function
| [] -> []
| x::xs -> let left,right = List.partition (fun el -> el <= x) xs
qsort left # [x] # qsort right
let rec qsortu = function
| [] -> []
| x::xs -> let left = List.filter (fun el -> el < x) xs
let right = List.filter (fun el -> el > x) xs
qsortu left # [x] # qsortu right
And a test in interactive mode:
> qsortu [42;42;42;42;42];;
val it : int list = [42]
> qsortu [5;4;4;3;3;3;2;2;2;2;1];;
val it : int list = [1; 2; 3; 4; 5]
> qsortu [3;1;4;1;5;9;2;6;5;3;5;8;9];;
val it : int list = [1; 2; 3; 4; 5; 6; 8; 9]
Since it's an interview question it is usually expected by the interviewer to be asked precisions about the problem.
With no alternative storage allowed (that is O(1) storage allowed in that you'll probably use some counters / pointers), it seems obvious that a destructive operation is expected, it might be worth pointing it out to the interviewer.
Now the real question is: do you want to preserve the relative order of the elements ? ie is this operation supposed to be stable ?
Stability hugely impact the available algorithms (and thus the complexity).
The most obvious choice is to list Sorting Algorithms, after all, once the data is sorted, it's pretty easy to get unique elements.
But if you want stability, you cannot actually sort the data (since you could not get the "right" order back) and thus I wonder if it solvable in less than O(N**2) if stability is involved.
doesn't use a hash table per se but i know behind the scenes it's an implementation of one. Nevertheless, thought I might post in case it can help. This is in JavaScript and uses an associative array to record duplicates to pass over
function removeDuplicates(arr) {
var results = [], dups = [];
for (var i = 0; i < arr.length; i++) {
// check if not a duplicate
if (dups[arr[i]] === undefined) {
// save for next check to indicate duplicate
dups[arr[i]] = 1;
// is unique. append to output array
results.push(arr[i]);
}
}
return results;
}
Let me do this in Python.
array1 = [1,2,2,3,3,3,4,5,6,4,4,5,5,5,5,10,10,8,7,7,9,10]
array1.sort()
print(array1)
current = NONE
count = 0
# overwriting the numbers at the frontal part of the array
for item in array1:
if item != current:
array1[count] = item
count +=1
current=item
print(array1)#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5, 5, 5, 5, 6, 7, 7, 8, 9, 10, 10, 10]
print(array1[:count])#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The most Efficient method is :
array1 = [1,2,2,3,3,3,4,5,6,4,4,5,5,5,5,10,10,8,7,7,9,10]
array1.sort()
print(array1)
print([*dict.fromkeys(array1)])#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#OR#
aa = list(dict.fromkeys(array1))
print( aa)#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]