Array OutOfBounds Exception with MergeSort - java

I am doing a simple MergeSort implementation taking it form a pseudocode. I use Java Generics for that purpose. However I get such exception on the last element in the first for-loop. I have already made some changes (hope for the better) but still this one inevitably comes up. Why is that so?
private Comparable[] mergesort(Comparable[] elements, int l, int r) {
if(l < r){
int m = (l + r - 1)/2;
mergesort(elements, l, m);
mergesort(elements, m + 1, r);
int i = l;
int j = m + 1;
int k = l;
Comparable[] elements1 = (Comparable[])new Comparable[l + r]; //changed from [l + r - 1] and in the function caller also mergesort(elements, elements.length - elements.length, elements.length - 1)
while(i <= m && j <= r){
if(elements[i].compareTo(elements[j]) <= 0 ){
elements1[k] = elements[i];
i++;
} else {
elements1[k] = elements[j];
j++;
}
k++;
}
for(int h = i; i <= m; h++){
elements[k + (h - i)] = elements[h];
//ArrayIndexOutOfBoundsException: 4(the length of the input array)
}
for(int h = j; h <= k - 1; h++){
elements[h] = elements1[h];
}
}
return elements;
}

While your code is hard to read, I think you are comparing the wrong value.
for(int h = i; i <= m; h++){
^
should be h
elements[k + (h - i)] = elements[h];
//ArrayIndexOutOfBoundsException: 4(the length of the input array)
}

You use:
for(int h = i; i <= m; h++) {
elements[k + (h - i)] = elements[h];
}
You always increase h but compare i <= m. Since you never change i you have an endless loop.

Related

binary search right should be nums.length or nums.length - 1?

I'm always confused with Binary search right boarder.
For example, if we want to find the last index of target in a sorted array, the code should be:
public int binarySearchLarger(int[] nums, int target) {
int l = 0;
int r = nums.length - 1;
while (l < r) {
int m = l + (r - l + 1) / 2;
if (nums[m] < target) l = m;
else if(nums[m] > target) r = m - 1;
else l = m;
}
if (nums[l] == target) return l;
else return -1;
}
but I see lots of posts said that if we want while(l<r), then r should be nums.length, in this case, the code becomes:
public int binarySearchLarger(int[] nums, int target) {
int l = 0;
int r = nums.length;
while (l < r) {
int m = l + (r - l + 1) / 2;
if (nums[m] < target) l = m;
else if(nums[m] > target) r = m - 1;
else l = m;
}
if (nums[l] == target) return l;
else return -1;
}
but in this case, if (nums[m] < target) l = m; will throw arrayindexoutofbound exception.
My questions is: when should we use r = nums.length - 1 and when should we use r = nums.length?
See this answer for a discussion about the various options when implementing binary search: Binary Search algorithm implementations
For your problem, which seems to be to find the last instance of the target, I do it like this:
int findLastIndexOfTarget(int[] nums, int toFind) {
// find the position that divides <= toFind from > toFind
// these are the lowest and highest possible indexes
int low = 0;
int high = nums.length;
// while there is a range of possible indexes
while(low<high) {
int test = low+((high-low)/2);
if (nums[test] <= toFind) {
//too low
low = test+1; //guaranteed > low, <= high
} else {
//not too low
high = test; //guaranteed >= low, < high
}
}
// guaranteed low == high
// We found the position we were looking for. See if the target is on the left
return (low > 0 && nums[low-1]==target) ? low-1 : -1;
}
I do it like this:
int findEndIndex( vector<int> &nums, int target ){
int l = 0, r = nums.size() - 1;
while( l < r ){
int m = (l + (r - l) / 2) + 1;
if( nums[m] == target )
l = m;
else if( nums[m] < target )
l = m + 1;
else
r = m - 1;
}
return l >= nums.size() || nums[l] != target ? -1 : l;
}

Leetcode 1044. Longest Duplicate Substring (small question in terms of modulus)

I was solving Leetcode 1044 and the answer is using binary search and rolling hash. Basically use binary search to select a length and then do a search for duplicate string of that length. Here rolling hash comes into play to save space (instead of using a set to store all substring, we store substring's hash). That is the background for the solution.
My question is in terms of the modulus used to prevent overflow. I chose Long.MAX_VALUE which I believe is big enough to handle it but the answer is not correct when I use Long.MAX_VALUE. However, when I use Long.MAX_VALUE / 26 or Math.pow(2, 32), they both work. Sorry I'm pretty bad about modulus and I think I definitely missed some things here. Could anyone shed some light on it? Thanks! The following is my solution:
public static long modulus = Long.MAX_VALUE / 26;
public String longestDupSubstring(String S) {
int n = S.length();
int l = 1;
int r = n - 1;
int index = -1;
while (l <= r) {
int m = l + (r - l) / 2;
int temp = findDuplicate(S, m);
if (temp != -1) {
index = temp;
l = m + 1;
}
else {
r = m - 1;
}
}
return index == -1 ? "" : S.substring(index, index + r);
}
private int findDuplicate(String s, int len) {
Set<Long> set = new HashSet<>();
long hash = 0;
long p = 1;
for (int i = 0; i < len; i++) {
hash = (hash * 26 + s.charAt(i) - 'a') % modulus;
p = (p * 26) % modulus;
}
set.add(hash);
for (int i = len; i < s.length(); i++) {
hash = (hash * 26 + (s.charAt(i) - 'a')
- (s.charAt(i - len) - 'a') * p) % modulus;
if (hash < 0) {
hash += modulus;
}
if (set.contains(hash)) {
return i - len + 1;
}
set.add(hash);
}
return -1;
}
26 is not part of the modulus, is part of hashing. If we would separate those in the algorithm, then we might see how it'd work. For modulus usually a large number would simply suffice, does not have to be a long:
public final class Solution {
int a = 26;
int mod = 1 << 29;
public final String longestDupSubstring(
final String s
) {
int lo = 1;
int hi = s.length() - 1;
while (lo <= hi) {
int mid = lo + ((hi - lo) >> 1);
int startIndex = search(s, mid);
if (startIndex == - 1) {
hi = mid - 1;
}
else {
lo = -~mid;
}
}
int startIndex = search(s, hi);
return startIndex == -1 ? "" : s.substring(startIndex, startIndex + hi);
}
public final int search(
final String s,
final int len
) {
long h = 0;
long aL = 1;
for (int i = 0; i < len; i++) {
h = (h * a % mod + s.charAt(i)) % mod;
aL = aL * a % mod;
}
HashMap<Long, List<Integer>> visited = new HashMap<>();
visited.put(h, new ArrayList<Integer>());
visited.get(h).add(0);
for (int i = 1; i < -~s.length() - len; i++) {
h = ((h * a % mod - s.charAt(i - 1) * aL % mod + mod) % mod + s.charAt(i + len - 1)) % mod;
if (visited.containsKey(h)) {
for (int start : visited.get(h)) {
if (s.substring(start, start + len).equals(s.substring(i, i + len))) {
return i;
}
}
} else {
visited.put(h, new ArrayList<Integer>());
}
visited.get(h).add(i);
}
return -1;
}
}

Index Outside of Bounds on Stock Maximization Algorithm

I have the following code translated as best I could from Java to C#:
public double maxProfit(double[] prices, int K)
{
if (K == 0 || prices.Length == 0)
{
return 0;
}
var dp = new double[K + 1, prices.Length];
for (int i = 1; i < K + 1; i++)
{
double maxDiff = -prices[0];
for (int j = 1; j < prices.Length; j++)
{
dp[i, j] = Math.Max(dp[i, j - 1], prices[j] + maxDiff);
maxDiff = Math.Max(maxDiff, dp[i - 1, j] - prices[j]);
}
}
printTrans(dp, prices, K);
return dp[K, prices.Length - 1];
}
public void printTrans(double[,] dp, double[] prices, int K)
{
int i = K - 1;
int j = prices.Length;
var priceList = new List<double>();
while (true)
{
if (i == 0 || j == 0)
{
break;
}
if (dp[i, j] == dp[i, j - 1])
{
j = j - 1;
}
else
{
priceList.Add(j);
double maxDiff = dp[i, j] - prices[j];
for (int z = j - 1; z >= 0; z--)
{
if (dp[i - 1, z] - prices[z] == maxDiff)
{
i = i - 1;
j = z;
priceList.Add(j);
break;
}
}
}
}
while (priceList.Count > 0)
{
Console.WriteLine("Buy # " + prices[priceList.IndexOf(0)]);
Console.WriteLine("Sell # " + prices[priceList.IndexOf(0)]);
}
}
Error occurs in the second method on lines:
if (dp[i, j] == dp[i, j - 1])
and
for (int z = j - 1; z >= 0; z--)
{
if (dp[i - 1, z] - prices[z] == maxDiff)
I am getting an Index was outside the bounds of the array. error. I understand what this error means but I have no clue on my to fix it. It took me quite a bit to understand the first part of this code but for the second part, I am at a loss.
Also what is the C# equivalent of the Java pollFirst() method?
Probably this line is the cause
public void printTrans(double[,] dp, double[] prices, int K)
{
int i = K - 1;
int j = prices.Length; // <=== this line is the cause
its causing the j to refer an index outside the bounds of the 2D array.
If you have ported from java recheck your java code.
Either make that line
int j = prices.Length - 1;
Or you need to make changes to how you create your array
var dp = new double[K + 1, prices.Length]; // <-- prices.Length would have to change here

Is it possible to implement a BubbleSort with only one cycle? (Not recursive)

What Im trying to implement is a BubbleSort/similar algorithm, but with just one single cycle.
What that means is, I want to change this:
for (i = 0; i < N - 1; i++)
for(j = i+1; j < N; j++)
//code
into this:
for (ij = 0; ij < N * (N - 1) / 2; ij++)
i = ?
j = ?
//code
The problem is, I need to implement the values of 'i' and 'j' manually. Does anybody know if this is possible?
Assuming you meant i+1, not 1+1, the code
for (i = 0; i < N - 1; i++)
for(j = i+1; j < N; j++)
//code
is equivalent to
int k = 2 * N - 1;
for (int ij = 0; ij < N * (N - 1) / 2; ij++) {
int i = (int) Math.floor((k - Math.sqrt(k * k - 8 * ij)) / 2);
int j = i + 1 + ij - (k - i) * i / 2;
//code
}
This is completely pointless though...
You could do it like this:
while (ij < N * (N - 1) / 2) {
j = (j + 1) % N;
if (j==0)
i++;
}
I don't see the benefit though
Here is a while-loop version, though I also don't see the point. Generally, you can turn almost anything into one loop by having a boolean that indicates whether to continue, and various if-tests to decide what to do inside the loop. If applied to a naturally nested loop algorithm, the result will be less readable and maintainable than using multiple loops.
public static void weirdSort(int[] data) {
boolean sortDone = false;
boolean swapDone = false;
if (data.length < 2) {
// Lengths 0 and 1 create special cases, and are already sorted.
return;
}
int i = 0;
while (!sortDone) {
if (data[i] > data[i + 1]) {
swapDone = true;
int temp = data[i + 1];
data[i + 1] = data[i];
data[i] = temp;
}
i++;
if (i == data.length - 1) {
sortDone = !swapDone;
swapDone = false;
i = 0;
}
}
}

Codility - Counting Elements Lessons : fastest algorithm swap

i am studying Codility chapter 2 : Counting elements.
I tried to make the exercise, and i think I have a good solution O(n). is It a valid solution ?
Is it a better solution that the BEST solution proposed in te lesson ?
Problem: You are given an integer m (1 􏰀 m 􏰀 1 000 000) and two non-empty, zero-indexed arrays A and B of n integers, a0,a1,...,an−1 and b0,b1,...,bn−1 respectively (0 􏰀 ai,bi 􏰀 m). The goal is to check whether there is a swap operation which can be performed on these arrays in such a way that the sum of elements in array A equals the sum of elements in array B after the swap. By swap operation we mean picking one element from array A and
one element from array B and exchanging them.
I tested my solution with these values :
int a[] = {2, 7, 12, 16};
int b[] = {4, 8, 9};
m = 16;
note: I commented the return to see the swapped values.
public int resultat(int[] A, int B[], int max) {
int sumA = Arrays.stream(A).sum();
int sumB = Arrays.stream(B).sum();
int[] countA = count(A, max);
int[] countB = count(B, max);
int diff = sumA - sumB;
int diffMin = 0;
if (diff % 2 != 0) {
return -1;
}
diffMin = diff / 2;
if (sumA > sumB) {
if (diff < countA.length && diffMin < countB.length && countA[diff] != 0 && countB[diffMin] != 0) {
System.out.println("A:" + diff + "- B:" + diffMin);
//return 1;
}
} else {
if (diffMin < countA.length && diff < countB.length && countB[diff] != 0 && countA[diffMin] != 0) {
System.out.println("A:" + diffMin + "- B:" + diff);
//return 1;
}
}
return -1;
}
public int[] count(int[] X, int max) {
int[] p = new int[max + 1];
Arrays.fill(p, 0);
for (int i = 0; i < X.length; i++) {
p[X[i]] += 1;
}
return p;
}
Your solution is O(n + m), because of count(A, max) and count(B, max) invocations. count() is linear.
It's not valid solution. Counter-example: A = [1, 2, 4], B = [3, 5, 1], m = 5. Answer is true, because we can swap 2 with 3. Your code throws ArrayIndexOutOfBoundsException: -2 on countB[diff], because diff is -2. Even if you secure it with, for example diff = Math.abs(sumA - sumB), the algorithm is still not correct and it will return false.
You don't need to do Arrays.fill(p, 0), int default value is 0.
Instead of p[X[i]] += 1 you could write p[X[i]]++.
Here's (i hope) a correct solution.
Please note, that counting can still be put after checking dif is not an odd number to make performance higher.
Note, too, that listA and listB arrays are used as the value at zero place is never used. This is for better understanding, too. We don't need the occurrence of the value 0 but we need the occurrence of max value.
public boolean solution(int[] A, int[] B, int max) {
int[] listA = new int[max+1];
int[] listB = new int[max+1];
int listAsum =0;
int listBsum=0;
for(int i = 0; i<A.length; i++){
listA[A[i]]++;
listAsum +=A[i];
listBsum +=B[i];
}
int diff = listAsum - listBsum;
if(diff%2 == 1) return false;
diff /=2;
for(int i=0; i<A.length; i++){
if((B[i] - diff) >= 0 && (B[i]-diff) <= max && listA[(B[i]-diff)] > 0) return true;
}
return false;
}
public boolean solution(int[] A, int[] B, int max) {
int[] count = new int[max + 1];//count(A, max);
int sum_a = 0; //Arrays.stream(A).sum();
int sum_b = 0;//Arrays.stream(B).sum();
for (int i = 0; i < A.length; i++) {
count[A[i]]++;
sum_a += A[i];
sum_b += B[i];
}
int d = sum_b - sum_a;
if (d % 2 == 1) return false;
d /= 2;
for (int i = 0; i < A.length; i++) {
if ((B[i] - d) >= 0 && (B[i] - d) <= max && count[(B[i] - d)] > 0)
return true;
}
return false;
}
public int[] count(int[] X, int max) {
int[] p = new int[max + 1];
Arrays.fill(p, 0);
for (int i = 0; i < X.length; i++) {
p[X[i]]++;
}
return p;
}

Categories