tag:blogger.com,1999:blog-86342005841505678162020-02-28T18:32:28.659-08:00Max's notesGiuseppe M. Mazzeohttp://www.blogger.com/profile/04161480776724627565noreply@blogger.comBlogger3125tag:blogger.com,1999:blog-8634200584150567816.post-91275218060170640952016-04-02T17:22:00.000-07:002016-04-05T08:28:19.177-07:00Random position of maximum of arrayProblem: return a (uniformly distributed) random position of the maximum value in a non-empty array of integers.<br /><br />Example: If a=[1,2,3,2,3,1,3], the positions of the maximum value (3) are 2, 4, and 6. One of these three values has to be randomly returned (each value has the same probability to be chosen).<br /><br />Solution: a simple solution is scanning the array, keeping a list of the positions of the currently found max. After the scan, one of these position is chosen randomly. This solution has linear time complexity, but requires auxiliary space that in the worst case could be of the same size of the array (all the elements are same).<br />A simple solution requiring constant auxiliary space could be obtained by scanning the array twice. The first time the maximum value <i>m</i> and the number of its occurrences <i>c</i> are found. Then, a random number <i>p</i> between 1 and <i>c</i> is chosen, and with a second scan, the position in which <i>m</i> is found for the <i>p-th</i> time is returned.<br /><br />The optimal solution requires constant auxiliary space and one only scan. While scanning the array, we keep the maximum value <i>m</i> and the number of its occurrences <i>c</i>. We also keep the chosen position <i>p</i> for <i>m</i>, that will be returned after the scan.<br />Each time we find a value greater than the current maximum <i>m</i>, we update <i>m</i>, set <i>c=1</i>, and set <i>p</i> to the current position. If we find another value equal to <i>m</i>, we increase <i>c</i> and set <i>p</i> to the new position with probability equal to <i>1/c</i>. At the end of the scan, each position in which <i>m</i> occurs will have been chosen with probability <i>1/c</i>, where <i>c</i> is the final count of occurrences of <i>m</i>.<br />This can be simply proven by induction. For <i>c=1</i> and <i>c=2</i>, it is obvious. So, assume that <i>p</i> was uniformly chosen among the first <i>c-1</i> occurrence of <i>m</i>, that is, <i>p</i> was correctly chosen with probability <i>1/(c-1)</i>. We choose the new position, that is the <i>c-th</i> position in which <i>m</i> has been found, with probability <i>1/c</i>, then, the probability of choosing again the old position <i>p</i> is <i>1-1/(c-1)=(c-1)/c</i>. Globally, the probability of choosing the old position is <i>(1/(c-1)) * ((c-1)/c) = 1/c</i>, which is the same of that used to choose the new position.<br /><br />The implementation of this algorithm is quite simple, and it is given in the following. <br /><br /><pre class="java" name="code">public int randomMaxPosition(int[] a) {<br /> int m=a[0];<br /> int c=1;<br /> int p=0;<br /> for (int i=1; i < a.length; i++) {<br /> if (a[i] > m) {<br /> m=a[i];<br /> c=1;<br /> p=i;<br /> } else if (a[i]==m) {<br /> c++;<br /> if (Math.random() < 1.0/c) {<br /> p=i;<br /> }<br /> }<br /> }<br /> return p;<br />}<br /></pre>Giuseppe M. Mazzeohttp://www.blogger.com/profile/04161480776724627565noreply@blogger.com0tag:blogger.com,1999:blog-8634200584150567816.post-57673531240704111242016-03-26T14:20:00.000-07:002016-04-02T14:22:30.310-07:00Array rotationProblem: left-rotate an array of k positions in place, in linear time and constant auxiliary space.<br /><br />Solution: If k=1, then we can save the first element in a temporary variable, write in each position, except the last one, the value in the subsequent position, and, finally, write the temporary variable in the last position.<br /><br />If k>1, we can use the same approach several times for different subsets (not subarrays!) of the array.<br />Assume that n is the length of the array and k<n (otherwise, we can set k=k%n).<br />We can save the first element in a temporary variable.<br />Then, starting from position p=0, we can write in that position the value in position (p+k)%n. Then set p=(p+k)%n and repeat until (p+k)%n is equal to 0.<br />When (p+k)%n is 0, in p we write the temporary variable, because in 0 we previously wrote the value in position p+k.<br />If k and n are co-prime, this approach enables to scan all the array (i.e., (p+k)%n becomes equal to 0 after n-1 iterations). In fact, being p=(l-1)*k, we have that (l*k)%n is 0 only if l is a multiple of n, when gcd(k,n)=1. Thus, p=0 when l=0 (at the beginning) and then when l becomes equal to n (i.e., after a complete scan).<br />Instead, if n and k are not co-prime, being nc=gcd(n,k)>1, after n/nc-1 iterations (p+k)%n will become 0. Therefore, not all the elements can be rotated in this way, but only n/nc.<br />However, if set p=1, and we iterate again until (p+k)%n is equal to 1, we can rotate other n/nc elements.<br />We can repeat this process nc times, setting the initial value of p to 0,1,...,nc-1, thus completing the rotation of all the elements of the array.<br /><br />A Java implementation is given in the following.<br /><br /><pre name="code" class="java"> <br />public int gcd(int a, int b) {<br /> if (b==0) {<br /> return a;<br /> }<br /> return gcd(b, a%b);<br />}<br /><br />public <T> void rotateArray(T[] a, int k) {<br /> k = k % a.length;<br /> int numberOfCycles=gcd(a.length, k);<br /> int lengthOfCycles=a.length/numberOfCycles;<br /> for (int i = 0; i < numberOfCycles; i++) { <br /> T temp = a[i];<br /> int p = i;<br /> for (int j = 0; j < lengthOfCycles-1; j++) {<br /> a[p%a.length] = a[(p + k)%a.length];<br /> p+=k;<br /> }<br /> a[p%a.length] = temp;<br /> }<br />}<br /></pre> Another nice solution is obtained by first inverting the subarray consisting of the first k elements, then then subarray consisting of the last n-k elements, and finally inverting the whole array.<br/>Each element with index i<k after the first inversion will be in position k-i-1, and after the third inversion in position n-1-k+i+1=n-k+i. Each element with index i≥k after the second inversion will be in position n-1-i+k, and after the third inversion in position n-1-n+1+i-k=i-k. The implementation of this algorithm is much simpler than the previous one.<br /><br/><pre name="code" class="java"><br />public <T> void invertSubarray(T[] a, int lo, int hi) {<br /> while (lo < hi) {<br /> T temp = a[lo];<br /> a[lo] = a[hi];<br /> a[hi] = temp;<br /> lo++;<br /> hi--;<br /> }<br />}<br /><br />public <T> void rotateArray(T[] a, int k) {<br /> k = k % a.length;<br /> invertSubarray(a, 0, k-1);<br /> invertSubarray(a, k, a.length-1);<br /> invertSubarray(a, 0, a.length-1);<br />}<br /></pre>Giuseppe M. Mazzeohttp://www.blogger.com/profile/04161480776724627565noreply@blogger.com0tag:blogger.com,1999:blog-8634200584150567816.post-82859894307372707822016-01-22T19:03:00.001-08:002016-04-19T18:06:09.858-07:00Median of two sorted arraysProblem: Let <i>a</i> and <i>b</i> be two sorted arrays. Find the median of the array that would be obtained by merging <i>a</i> and <i>b</i>.<br /><br />Note: The median of a sorted array with an even number of elements is the average of the two elements in the middle of the array. E.g., the median of (1,2,3,4) is (2+3)/2=2.5<br /><br />Solution: A naive solution would be processing <i>a</i> and <i>b</i> using the same technique of the merge routine of the merge-sort algorithm. We do not need to materialize the merged array, we can just save the element/s that would be in the middle. This approach requires <i>O(|a|+|b|)</i> time and constant auxiliary space.<br /><br />Indeed, the problem can be solved in time <i>O(log(|a|)+log(|b|))</i> and constant auxiliary space. <br /><br />Let's think to a simple case that can be solved in constant time. Assume that the size of one of the arrays, say <i>a</i>, as length not greater then 2 (<i>|a| ≤ 2</i>). By means of some examples, it is easy to see that we can focus our attention the three (<i>|b|</i> is odd) or four (<i>|b|</i> is even) elements in the middle of <i>b</i>, or all the elements of <i>b</i>, if <i>|b|<3</i>.<br />In this case, the naive approach can be applied, and since it will work on at most 6 elements, whatever <i>|a|+|b|</i> is, its complexity can be considered constant.<br />Summarizing, we are able to solve the problem in constant time and space when one array has at most two elements, whatever the size of the other array is.<br /><br />Now, lets try to efficiently reduce the general problem to the above situation, i.e., one of the two arrays has size not larger than two. Let <i>m<sub>a</sub></i> and <i>m<sub>b</sub></i> be the median of <i>a</i> and <i>b</i>, respectively. We can observe that if <i>m=m<sub>a</sub>=m<sub>b</sub></i>, then <i>m</i><sub> </sub>is also the value of the median of merged array.<br />But assume that we are not so lucky, and <i>m<sub>a</sub><m<sub>b</sub></i> (the case <i>m<sub>a</sub>>m<sub>b</sub></i> can be handled symmetrically).<br />Let <i>h</i> be the minimum between the number of elements on the left of <i>m<sub>a</sub></i> and the number of elements on the right of <i>m<sub>b</sub></i>. The global median cannot be either in the first <i>h</i> elements of <i>a</i> or in the last <i>h</i> elements of <i>b</i>.<br />An informal intuition is the following. Being <i>a<sub>h</sub></i> the <i>h-th</i> element of <i>a</i>, the number of elements less than <i>a<sub>h</sub></i> in <i>a</i> plus the number of elements less than <i>a<sub>h</sub></i> in <i>b</i> is less than one half of <i>|a|+|b|</i>. Similarly, being <i>b<sup>h</sup></i> the <i>h-th</i> last element of <i>b</i>, the number of elements greater than <i>b<sup>h</sup></i> in <i>b</i> plus the number of elements greater than <i>b<sup>h</sup></i> in <i>b</i> is less than one half of <i>|a|+|b|</i>.<br />Thus, we can discard the first <i>h</i> elements of <i>a</i> and the last <i>h</i> elements of <i>b</i>. Observe that, in this way, the length of at least one array has been halved (indeed, it is almost halved, since the median element/s is/are kept). We do not actually need to remove the elements of the arrays. We can just keep two indexes for each array, denoting the lower and upper bound of the range that can contain the global median.<br /><br /><pre class="java" name="code">//median of the elements of a with index between lo and hi<br />public double median(int[] a, int[] r) {<br /> return (a[(r[0] + r[1]) / 2] + a[(r[0] + r[1] + 1) / 2]) * 0.5;<br />}<br /><br />//naive O(|a|+|b|) algorithm<br />public double naiveMedian(int[] a, int[] ra, int[] b, int[] rb) {<br /> int totalLength = ra[1] - ra[0] + 1 + rb[1] - rb[0] + 1;<br /> int pos1 = (totalLength - 1) / 2;<br /> int pos2 = totalLength / 2; //when totalLength is odd, pos1=pos2<br /> int i = ra[0];<br /> int j = rb[0];<br /> int k=0;<br /> double median = 0;<br /> while (k <= pos2) {<br /> if (i <= ra[1] && (j>rb[1] || a[i] <= b[j]) ) {<br /> if (k == pos1 || k == pos2) {<br /> median += a[i];<br /> }<br /> i++;<br /> } else {<br /> if (k == pos1 || k == pos2) {<br /> median += b[j];<br /> }<br /> j++;<br /> }<br /> k++;<br /> }<br /> if (pos1 != pos2) {<br /> median *= 0.5;<br /> }<br /> return median;<br />}<br /><br />public double efficientMedian(int[] a, int[] b) {<br /> int[] ra = new int[]{0, a.length - 1}; //range of a<br /> int[] rb = new int[]{0, b.length - 1}; //range of b<br /> if (ra[1] < ra[0]) { //a is empty<br /> return median(b, rb);<br /> }<br /> if (rb[1] < rb[0]) { //b is empty<br /> return median(a, ra);<br /> }<br /> double ma = median(a, ra);<br /> double mb = median(b, rb);<br /> while (ma != mb && ra[1] - ra[0] > 1 && rb[1] - rb[0] > 1) {<br /> int delta = Math.min(ra[1] - ra[0], rb[1] - rb[0]) / 2;<br /> if (ma < mb) { //ignore the leftmost elements of a and the rightmost elements of b<br /> ra[0] += delta;<br /> rb[1] -= delta;<br /> } else { //ignore the rightmost elements of a and the leftmost elements of b<br /> rb[0] += delta;<br /> ra[1] -= delta;<br /> }<br /> ma = median(a, ra);<br /> mb = median(b, rb);<br /> }<br /> if (ma == mb) {<br /> return ma;<br /> }<br /> if (ra[1] - ra[0] <= 1) { //restrict the subarray of b to its elements in the middle<br /> return naiveMedian(a, ra, b, restrictRange(rb));<br /> } else { //rb[1] - rb[0] <= 1<br /> return naiveMedian(a, restrictRange(ra), b, rb);<br /> }<br />}<br /><br />public int[] restrictRange(int[] r) {<br /> if (r[1] - r[0] <= 1) {<br /> return r;<br /> }<br /> int mid = (r[0] + r[1]) / 2;<br /> return new int[]{mid - 1, (r[1] - r[0]) % 2 == 0 ? mid + 1 : mid + 2};<br />}<br /></pre>Giuseppe M. Mazzeohttp://www.blogger.com/profile/04161480776724627565noreply@blogger.com0