Recursive method to count number of odd integers in array - java

I need to write a recursive method to count the number of odd integers in an array.
Here's my code so far:
public static int countOdd(int[] numbers, int startIndex, int endIndex) {
if (startIndex == endIndex) {
if (numbers[startIndex] % 2 != 0) {
return 1;
} else {
return 0;
}
} else {
return countOdd(numbers, startIndex, endIndex - 1);
}
}

Your recursive line is incorrect:
return countOdd(numbers, startIndex, endIndex - 1);
You've lost whether the endIndex is odd. This would help:
return countOdd(numbers, startIndex, endIndex - 1) +
countOdd(numbers, endIndex, endIndex);
And I'm not sure if you're calling it right, I'm assuming it would be:
countOdd(numbers, 0, numbers.length-1);
Explainer: In order to understand how to implement it, you need to break the problem down. If I want to recursively count the odd numbers in an array:
[a, b, c, d, e, f, g, .... z]
The code above basically does this:
countOdd([a, b, c, d, e, f, g, ...y]) + countOdd([z])
Notice second operand will return 0 or 1 because the subset is of size 1. The first operand basically is length 1 smaller. Recursion continues:
countOdd([a, b, c, d.... x]) + countOdd([y]) + countOdd([z])
...
countOdd([a]) + countOdd([b]) + countOdd([c]) + ... countOdd([z])
And once they are all size 1 subsets, it can calculate it.
0 + 1 + 0 + 1 + 1 ..
And return the result from summing individual counts of odd digits.
Extra Notes: Notice that the recursion could be done differently, but still come up with the same result (eg.:
return countOdd(numbers, startIndex, startIndex) +
countOdd(numbers, startIndex + 1, endIndex);

Can you please try:
<your main class>{
//global variables
int index = 0;
int[] array = {1,2,3,4,5};
int counter = 0;
int totalOfOddNumbers = countOddIntegers(index);
System.out.println(totalOfOddNumbers);
}
private int countOddIntegers(int i){
if (array[i] == 1) || (array[i]%2 != 0) counter ++;
if (i != array.length - 1) return countOddIntegers(i+1);
else return counter;
}

Related

Recursion sum numbers *with rule* - Recursion only

So the exercise is:
Using recursion only (no loops)
Find if there is sub ground of numbers that are equal to the given number in an array and follow the rule.
Let's say I have this array, I give the function a number for sum and it must adhere to this rule:
you cannot repeat the same number, and you can't sum 3 numbers in a row (can't do i+1 and i+2)
int[] a = {5,4,2,1,3};
So in this case:
num 8 = true (4+3+1) ( 5+3)
num 11 = false (4+5+2 are 3 but are three in a row) (5+2+1+3 also three in a row)
My attempt is:
public static boolean sumRule(int[] a , int num){
if (num == 0){
return true;
} else {
return sumRule(a,num,0,a.length);
}
}
private static boolean sumRule(int[] a, int num, int low,int high){
if(low >= high || low < 0){
return false;
}
if (a[low] == -1){
return false;
}
if(a[low] == num || num-a[low] == 0 ){
return true;
}
int temp = a[low];
a[low] = -1;
return sumRule(a,num,low,high) || sumRule(a,num-temp,low+3,high) || sumRule(a,num-temp,low+1,high) ;
}
But when I send 11 to this, it still returns true, anyone has an idea what am i missing here?
Thanks,
I have the full code answer below, and here's the explanation:
Essentially you need to break this problem down to a recurrence. What that means is, you look at the choice at each step (i.e. whether to use a number or not in the sum) and recursively calculate both options.
The base case:
If num == 0 then we know it's true. But if num != 0 and the array has length 0, then we know it's false
Recursive case:
We check if the first number in the array is less than or equal to num. If not, then we can't use it. So we do a recursive call with all the same parameters except the array is now the original array minus the first number
If we CAN use the number (i.e. a[0] <= num) then the true answer might use this or it may not use it. We make a recursive call for each case, and return true if either of the recursive calls return true.
The consecutive number rule:
This is easy to enforce. We add a parameter called 'left' which tells us the number of elements we can consecutively take from the beginning of the array. To start with, left is 2 because at most we can take 2 consecutive numbers. Then in the cases where we DO use the first number in the array in our sum, we decrement left. If we don't use the first number in the array, we reset left to 2. In the cases where left becomes 0, we have no choice but to skip the current number at the top of the array.
class Main {
public static void main(String[] args) {
int[] a = new int[] {5,4,2,1,3};
System.out.println(sumRule(a, 8));
System.out.println(sumRule(a, 11));
}
public static boolean sumRule(int[] a , int num){
if (num == 0){
return true;
} else {
return sumRule(a,num,2);
}
}
private static boolean sumRule(int[] a, int num, int left){
if (num == 0) {
return true;
}
if (a.length == 0) {
return false;
}
int[] a_new = new int[a.length-1];
for (int i = 1; i < a.length; i++) a_new[i-1] = a[i];
if (left == 0) {
return sumRule(a_new, num, 2);
}
boolean using_a0 = false;
if (a[0] <= num) {
using_a0 = sumRule(a_new, num-a[0], left-1);
}
boolean not_using_a0 = sumRule(a_new, num, 2);
return (not_using_a0 || using_a0);
}
}
Edit - A variation on the code above without copying the array:
class Main {
public static void main(String[] args) {
int[] a = new int[] {5,4,2,1,3};
System.out.println(sumRule(a, 8));
System.out.println(sumRule(a, 11));
}
public static boolean sumRule(int[] a , int num){
if (num == 0){
return true;
} else {
return sumRuleNoLoop(a,num,2,0);
}
}
private static boolean sumRuleNoLoop(int[] a, int num, int left, int startIdx){
if (num == 0) {
return true;
}
if (startIdx >= a.length) {
return false;
}
if (left == 0) {
return sumRuleNoLoop(a, num, 2, startIdx+1);
}
boolean using_a0 = false;
if (a[startIdx] <= num) {
using_a0 = sumRuleNoLoop(a, num-a[startIdx], left-1, startIdx+1);
}
boolean not_using_a0 = sumRuleNoLoop(a, num, 2, startIdx+1);
return (not_using_a0 || using_a0);
}
}
First thing you can add is a check to see not 3 numbers in a row being added. Also replacing a number in the array with -1 would have unintended side effects within recursive calls. Below is something I have. You can ignore the index param I have used to see the values used.
Explanation:
The recursive sumRule method divides the problem into two parts:
First part takes the value of current index and adds with the sum of values starting from next index.
Second part assumes, current value can’t be taken for the sum. It only checks if there is a sum within the subset starting from next value of the array.
In the method, lastIndex is keeping track of the index of last value picked up for the sum. So, in the first call the value is 0, 1 in second and so on.
(start - lastIndex <= 1 ? consecutive + 1 : 1) is to check whether value of consecutive should be increased or not. consecutive = 1 means, current value is added to the sum.
public static boolean sumRule(int[] a, int num) {
if (num == 0) {
return true;
} else {
return sumRule(a, num, 0, 0, 0, 0, "");
}
}
public static boolean sumRule(final int[] a, int num, int sum, int start, int consecutive, int lastIndex,
String index) {
if (consecutive == 3) {
return false;
}
if (sum == num) {
System.out.println(index);
return true;
}
if (start >= a.length) {
return false;
}
return sumRule(a, num, sum + a[start], start + 1, (start - lastIndex <= 1 ? consecutive + 1 : 1), start,
index + ", " + start) || sumRule(a, num, sum, start + 1, consecutive, lastIndex, index);
}
Here is my implementation. It contains comments explaining what the different parts do.
public class RecurSum {
/**
* Determines whether 'sum' equals 'target'.
*
* #param arr - its elements are summed
* #param sum - sum of some elements in 'arr'
* #param target - required value of 'sum'
* #param index - index in 'arr'
* #param consecutive - number of consecutive indexes summed to ensure don't exceed 3
* #param start - starting element in 'arr' which is used for back-tracking
*
* #return "true" if 'sum' equals 'target'
*/
private static boolean sumRule(int[] arr, int sum, int target, int index, int consecutive, int start) {
if (sum == target) {
return true;
}
else {
if (index >= arr.length) {
// if we have reached last element in 'arr' then back-track and start again
if (start < arr.length) {
return sumRule(arr, 0, target, start + 1, 0, start + 1);
}
// we have reached last element in 'arr' and cannot back-track
return false;
}
else {
consecutive++;
if (consecutive == 3) {
// skip 3rd consecutive element (because of the rule)
consecutive = 0;
return sumRule(arr, sum, target, index + 2, consecutive, start);
}
else {
if (sum + arr[index] > target) {
// recursive call but don't add current element of 'arr'
return sumRule(arr, sum, target, index + 1, 0, start);
}
// recursive call: add current element of 'arr' to 'sum' and proceed to next element
return sumRule(arr, sum + arr[index], target, index + 1, consecutive, start);
}
}
}
}
public static void main(String[] args) {
int[] arr = new int[]{5, 4, 2, 1, 3};
// initial call to recursive method with target = 11 (eleven)
System.out.println(sumRule(arr, 0, 11, 0, 0, 0));
// initial call to recursive method with target = 8
System.out.println(sumRule(arr, 0, 8, 0, 0, 0));
}
}

Correct way of Binary Search Algorithm

I just learned about the Binary Search algorithm and I tried to implement it. I have used a few test cases and it seems to work fine. However, when I checked on GeeksforGeeks, there are quite a few differences in the way they handled the indexing. Can anyone shed some lights on whether my implementation is good or not. And if not, how would it fail to work?
Here's my code:
static int binarySearch(int arr[], int i, int r, int x) {
if(r > 1) {
int middle = r/2;
if(arr[middle] == x) {
return middle;
}
if(arr[middle] > x) {
return binarySearch(arr, i, middle, x);
}else {
return binarySearch(arr, middle, r+1, x);
}
}
return -1;
}
Suppose that our function is going to do a binary search on the subarray arr[l..r] (inclusive). Here, r - l + 1 is the length of this subarray and when it's not a positive number (or r < l), we don't have a valid subarray and we can't search for anything, so the function stops the recursion and returns -1.
You know, we always make two subarrays with (almost) equal length. So, middle = r/2 is not correct and middle = (l + r) / 2 is correct. The new subarrays are arr[l..middle-1] and arr[middle+1..r]. We divide the subarray after checking its middle element, so these two subarrays should not contain the middle index as you see.
Now, we can rewrite your code.
static int binarySearch(int arr[], int l, int r, int x) {
if (r >= l) {
int middle = (l + r) / 2; //int middle = l + (r - l) / 2; for avoiding integer overflow
if(arr[middle] == x)
return middle;
if (arr[middle] > x)
return binarySearch(arr, l, middle - 1, x);
else
return binarySearch(arr, middle + 1, r, x);
}
return -1;
}
And this is a non-recursive version of binary search algorithm. Usually, it can work slightly faster.
static int binarySearch2(int arr[], int l, int r, int x) {
while (r >= l) {
int middle = (l + r) / 2; //int middle = l + (r - l) / 2; for avoiding integer overflow
if (arr[middle] == x)
return middle;
if (arr[middle] > x)
r = middle - 1;
else
l = middle + 1;
}
return -1;
}
Don't forget to sort your array before calling these functions.
Suppose that n is the length of the given array.
For 0-based arrays, the correct form of calling the functions is this:
binarySearch(arr, 0, n - 1, x);
and
binarySearch2(arr, 0, n - 1, x);
For 1-based arrays, the correct form of calling the functions is this:
binarySearch(arr, 1, n, x);
and
binarySearch2(arr, 1, n, x);

Recursion Logical Error Java

I have this assignment for school and it wants me to use recursion. I'm new to recursion and I understand it but I just can't figure out why this method isn't working the way it's suppose to. These are the instructions that were given to me and this is my code
// This method will be completed by the student!
// The student should implement the binary search algorithm using recursion. The
// method will originally be called by the GUI logic when the Search button is clicked.
public int binarySearch(Integer[] targetArray, int targetValue, int lowIndex, int highIndex){
if (lowIndex > highIndex)
return -1;
int midIndex = lowIndex + (highIndex - lowIndex)/2;
if (targetValue == targetArray[midIndex])
return midIndex;
if(targetArray[midIndex] > targetValue)
binarySearch(targetArray, targetValue, lowIndex, midIndex - 1);
else if(targetArray[midIndex] < targetValue)
binarySearch(targetArray, targetValue, midIndex + 1, highIndex);
return -1; // replace this with your recursive binary search code
}
The program will ask the user to enter in a target value. It will then search an array using recursion to tell if the target value is in the array. The array holds the numbers {1, 3, 5, 6, 8, 9, 10, 12, 14, 15}. When I search for the number 5 a message box pops up and says "Number 5 not found!" but when I set the target value to 8 it finds it in the array
I take it the comment stems from the review?
public int binarySearch(int[] targetArray, int targetValue,
int lowIndex, int highIndex) {
if (lowIndex > highIndex)
return -1;
int midIndex = lowIndex + (highIndex - lowIndex)/2;
if (targetValue == targetArray[midIndex])
return midIndex;
if (targetArray[midIndex] > targetValue)
return binarySearch(targetArray, targetValue, lowIndex, midIndex - 1);
else //if(targetArray[midIndex] < targetValue)
return binarySearch(targetArray, targetValue, midIndex + 1, highIndex);
}
The solution is to remove the last else-if.
Also you did not return the results of the recursively found index.
(An int[] parameter instead of Integer[] would be better.)
Also normally (99% of the) programmers use {} with if.
Well I have figured out the solution. The if-else statement was suppose to return the values at the end.
public int binarySearch(Integer[] targetArray, int targetValue, int lowIndex, int highIndex){
if (lowIndex > highIndex)
return -1;
int midIndex = lowIndex + (highIndex - lowIndex)/2;
if (targetValue == targetArray[midIndex])
return midIndex;
if(targetArray[midIndex] > targetValue)
return binarySearch(targetArray, targetValue, lowIndex, midIndex - 1);
else //if(targetArray[midIndex] < targetValue)
return binarySearch(targetArray, targetValue, midIndex + 1, highIndex);
//return -1; // replace this with your recursive binary search code
}

Error in program when parsing negative integers into an array

I am having a strange issue with one of my assignments. I am attempting to take integers from user input and store them in an array. After that, four recursive methods will be run on them to find different characteristics of those numbers. However, whenever I attempt to run the program with a negative integer in any of the indexes the program stops responding.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Assignment9 {
public static void main(String[] args) throws IOException {
int index = 0;
int[] numbers;
numbers = new int[100];
InputStreamReader inRead = new InputStreamReader(System.in);
BufferedReader buffRead = new BufferedReader(inRead);
String line = buffRead.readLine();
try {
while (!line.equals("0") && index < 100) {
numbers[index] = Integer.parseInt(line);
index++;
line = buffRead.readLine();
}
} catch (IOException exception) {
System.out.println("Array index out of bound");
}
` int min = findMin(numbers, 0, numbers.length - 1);
int sumAtEven = computeSumAtEvenIndexes(numbers, 0, numbers.length - 1);
int divByThree = countDivisibleBy3(numbers, 0, numbers.length - 1);
System.out.println("The minimum number is " + min);
System.out.println("The sum of numbers at even indexes is " + sumAtEven);
System.out.println("The count of numbers that are divisible by 3 is " + divByThree);
System.out.println("The maximum number among numbers that are less than the first number is " + maxLessThanFirst);
}
public static int findMin(int[] numbers, int startIndex, int endIndex) {
if (startIndex == endIndex) {
return numbers[startIndex];
} else if (findMin(numbers, startIndex, endIndex - 1) < numbers[endIndex]) {
return findMin(numbers, startIndex, endIndex - 1);
} else {
return numbers[endIndex];
}
}
public static int computeSumAtEvenIndexes(int[] numbers, int startIndex, int endIndex) {
if (startIndex == endIndex) {
if (startIndex % 2 == 0) {
return numbers[startIndex];
} else return 0;
} else {
if (endIndex % 2 == 0) {
return computeSumAtEvenIndexes(numbers, startIndex, endIndex - 1) + numbers[endIndex];
} else {
return computeSumAtEvenIndexes(numbers, startIndex, endIndex - 1);
}
}
}
public static int countDivisibleBy3(int[] numbers, int startIndex, int endIndex) {
if (startIndex == endIndex) {
if (numbers[startIndex] % 3 == 0) {
return 1;
} else {
return 0;
}
} else {
if (numbers[endIndex] == 0) {
return countDivisibleBy3(numbers, startIndex, endIndex - 1);
}
if (numbers[endIndex] % 3 == 0) {
return countDivisibleBy3(numbers, startIndex, endIndex - 1) + 1;
} else {
return countDivisibleBy3(numbers, startIndex, endIndex - 1);
}
}
}
}
This is the only relevant section of code that is necessary to understand the problem, I believe. If additional code is needed just ask. Thank you!
Replace your findMin method. Pass the array and zero for the index;
public static int findMin(int[] numbers, int index) {
if (index == numbers.length - 1)
{
return numbers[index];
}
else
{
return Math.min(numbers[index], findMin(numbers, index + 1));
}
}
Your findMin method is doubly recursive:
public static int findMin(int[] numbers, int startIndex, int endIndex) {
if (startIndex == endIndex) {
return numbers[startIndex];
// in the next line, we recurse looking for the minimum
} else if (findMin(numbers, startIndex, endIndex - 1) < numbers[endIndex]) {
// we've found the minimum, but now we must recurse again to get it!
return findMin(numbers, startIndex, endIndex - 1);
} else {
return numbers[endIndex];
}
}
This transforms what should be a linear algorithm into an exponential one. If you log each time findMin is entered, you will find it increases rapidly with the size of the array. Experimentation shows that it is called 2^(x-1) + 2^(x-2) - 1 times, where x is the length of the array.
So if you had an array of size 10, it would be called 767 times. For an array of size 20, it would be called 786,431 times. Size 30, 25,165,823 times. Size 100 yields:
950,737,950,171,172,051,122,527,404,031 calls (950 octillion, 9.5 x 10^29).
Your program will not crash with a StackOverflowError because at no time does the stack depth exceed roughly the length of the array (plus one for the main), but it will take longer than the lifespan of the universe to run.
Changing findMin to this:
public static int findMin(int[] numbers, int startIndex, int endIndex) {
if (startIndex == endIndex) {
return numbers[startIndex];
}
// there's no need for an else since the if ended with a return
int r = findMin(numbers, startIndex, endIndex - 1); // only recurse once
if (r < numbers[endIndex]) {
// we've found the minimum, return it without recursing again
return r;
}
// again, no need for else, here
return numbers[endIndex];
}
Now the algorithm only takes 20 calls for an array of size 20, 50 for size 50, 100 for size 100. The fact that you had already called findMin recursively to get the value to compare but were then calling it again to get the same value to return should have been a red flag. In many cases, such unnecessary repetition would merely be a minor annoyance; in this case, it was catastrophic.
Oh, I forgot to mention. The reason entering a negative number triggered the problem: Presumably, you don't always type 100 numbers in. I never did when I tried your program. It's too boring, and you can just end the list by entering a zero. When you allocate the array:
int[] numbers = new int[100];
The array is filled with zeros. So, if you enter ten numbers, the rest of the array will be zeros, and when we get to this line in the first call to findMin:
if (findMin(numbers, startIndex, endIndex - 1) < numbers[endIndex])
The number at the end will be zero, which is also the min. So we only recurse once, not twice. That will happen for most of the recursive calls, too; it will happen for all the ones at the long tail of zeros at the end of the array. It will only be when we get down into the entries where the user has actually entered a value where we will see the doubly-recursive behavior. If the user only enters about 10 numbers, we're safe.
But if the user enters even a single negative number, then that becomes the minimum and the zeros don't protect us. We hit the double recursion on every call, except for the one where numbers[endIndex] holds that negative number. Come to think of it, the reason I got 2^(x-1) + 2^(x-2) - 1 instead of just 2^x - 1 is because I always put the negative number in the second position in the array. So, depending on where the minimum value is, you could get performance better, or even worse, than what I describe above.

Using Binary Search with sorted Array with duplicates [duplicate]

This question already has answers here:
Finding multiple entries with binary search
(15 answers)
Closed 3 years ago.
I've been tasked with creating a method that will print all the indices where value x is found in a sorted array.
I understand that if we just scanned through the array from 0 to N (length of array) it would have a running time of O(n) worst case. Since the array that will be passed into the method will be sorted, I'm assuming that I can take advantage of using a Binary Search since this will be O(log n). However, this only works if the array has unique values. Since the Binary Search will finish after the first "find" of a particular value. I was thinking of doing a Binary Search for finding x in the sorted array, and then checking all values before and after this index, but then if the array contained all x values, it doesn't seem like it would be that much better.
I guess what I'm asking is, is there a better way to find all the indices for a particular value in a sorted array that is better than O(n)?
public void PrintIndicesForValue42(int[] sortedArrayOfInts)
{
// search through the sortedArrayOfInts
// print all indices where we find the number 42.
}
Ex: sortedArray = { 1, 13, 42, 42, 42, 77, 78 } would print: "42 was found at Indices: 2, 3, 4"
You will get the result in O(lg n)
public static void PrintIndicesForValue(int[] numbers, int target) {
if (numbers == null)
return;
int low = 0, high = numbers.length - 1;
// get the start index of target number
int startIndex = -1;
while (low <= high) {
int mid = (high - low) / 2 + low;
if (numbers[mid] > target) {
high = mid - 1;
} else if (numbers[mid] == target) {
startIndex = mid;
high = mid - 1;
} else
low = mid + 1;
}
// get the end index of target number
int endIndex = -1;
low = 0;
high = numbers.length - 1;
while (low <= high) {
int mid = (high - low) / 2 + low;
if (numbers[mid] > target) {
high = mid - 1;
} else if (numbers[mid] == target) {
endIndex = mid;
low = mid + 1;
} else
low = mid + 1;
}
if (startIndex != -1 && endIndex != -1){
for(int i=0; i+startIndex<=endIndex;i++){
if(i>0)
System.out.print(',');
System.out.print(i+startIndex);
}
}
}
Well, if you actually do have a sorted array, you can do a binary search until you find one of the indexes you're looking for, and from there, the rest should be easy to find since they're all next to each-other.
once you've found your first one, than you go find all the instances before it, and then all the instances after it.
Using that method you should get roughly O(lg(n)+k) where k is the number of occurrences of the value that you're searching for.
EDIT:
And, No, you will never be able to access all k values in anything less than O(k) time.
Second edit: so that I can feel as though I'm actually contributing something useful:
Instead of just searching for the first and last occurrences of X than you can do a binary search for the first occurence and a binary search for the last occurrence. which will result in O(lg(n)) total. once you've done that, you'll know that all the between indexes also contain X(assuming that it's sorted)
You can do this by searching checking if the value is equal to x , AND checking if the value to the left(or right depending on whether you're looking for the first occurrence or the last occurrence) is equal to x.
public void PrintIndicesForValue42(int[] sortedArrayOfInts) {
int index_occurrence_of_42 = left = right = binarySearch(sortedArrayOfInts, 42);
while (left - 1 >= 0) {
if (sortedArrayOfInts[left-1] == 42)
left--;
}
while (right + 1 < sortedArrayOfInts.length) {
if (sortedArrayOfInts[right+1] == 42)
right++;
}
System.out.println("Indices are from: " + left + " to " + right);
}
This would run in O(log(n) + #occurrences)
Read and understand the code. It's simple enough.
Below is the java code which returns the range for which the search-key is spread in the given sorted array:
public static int doBinarySearchRec(int[] array, int start, int end, int n) {
if (start > end) {
return -1;
}
int mid = start + (end - start) / 2;
if (n == array[mid]) {
return mid;
} else if (n < array[mid]) {
return doBinarySearchRec(array, start, mid - 1, n);
} else {
return doBinarySearchRec(array, mid + 1, end, n);
}
}
/**
* Given a sorted array with duplicates and a number, find the range in the
* form of (startIndex, endIndex) of that number. For example,
*
* find_range({0 2 3 3 3 10 10}, 3) should return (2,4). find_range({0 2 3 3
* 3 10 10}, 6) should return (-1,-1). The array and the number of
* duplicates can be large.
*
*/
public static int[] binarySearchArrayWithDup(int[] array, int n) {
if (null == array) {
return null;
}
int firstMatch = doBinarySearchRec(array, 0, array.length - 1, n);
int[] resultArray = { -1, -1 };
if (firstMatch == -1) {
return resultArray;
}
int leftMost = firstMatch;
int rightMost = firstMatch;
for (int result = doBinarySearchRec(array, 0, leftMost - 1, n); result != -1;) {
leftMost = result;
result = doBinarySearchRec(array, 0, leftMost - 1, n);
}
for (int result = doBinarySearchRec(array, rightMost + 1, array.length - 1, n); result != -1;) {
rightMost = result;
result = doBinarySearchRec(array, rightMost + 1, array.length - 1, n);
}
resultArray[0] = leftMost;
resultArray[1] = rightMost;
return resultArray;
}
Another result for log(n) binary search for leftmost target and rightmost target. This is in C++, but I think it is quite readable.
The idea is that we always end up when left = right + 1. So, to find leftmost target, if we can move right to rightmost number which is less than target, left will be at the leftmost target.
For leftmost target:
int binary_search(vector<int>& nums, int target){
int n = nums.size();
int left = 0, right = n - 1;
// carry right to the greatest number which is less than target.
while(left <= right){
int mid = (left + right) / 2;
if(nums[mid] < target)
left = mid + 1;
else
right = mid - 1;
}
// when we are here, right is at the index of greatest number
// which is less than target and since left is at the next,
// it is at the first target's index
return left;
}
For the rightmost target, the idea is very similar:
int binary_search(vector<int>& nums, int target){
while(left <= right){
int mid = (left + right) / 2;
// carry left to the smallest number which is greater than target.
if(nums[mid] <= target)
left = mid + 1;
else
right = mid - 1;
}
// when we are here, left is at the index of smallest number
// which is greater than target and since right is at the next,
// it is at the first target's index
return right;
}
I came up with the solution using binary search, only thing is to do the binary search on both the sides if the match is found.
public static void main(String[] args) {
int a[] ={1,2,2,5,5,6,8,9,10};
System.out.println(2+" IS AVAILABLE AT = "+findDuplicateOfN(a, 0, a.length-1, 2));
System.out.println(5+" IS AVAILABLE AT = "+findDuplicateOfN(a, 0, a.length-1, 5));
int a1[] ={2,2,2,2,2,2,2,2,2};
System.out.println(2+" IS AVAILABLE AT = "+findDuplicateOfN(a1, 0, a1.length-1, 2));
int a2[] ={1,2,3,4,5,6,7,8,9};
System.out.println(10+" IS AVAILABLE AT = "+findDuplicateOfN(a2, 0, a2.length-1, 10));
}
public static String findDuplicateOfN(int[] a, int l, int h, int x){
if(l>h){
return "";
}
int m = (h-l)/2+l;
if(a[m] == x){
String matchedIndexs = ""+m;
matchedIndexs = matchedIndexs+findDuplicateOfN(a, l, m-1, x);
matchedIndexs = matchedIndexs+findDuplicateOfN(a, m+1, h, x);
return matchedIndexs;
}else if(a[m]>x){
return findDuplicateOfN(a, l, m-1, x);
}else{
return findDuplicateOfN(a, m+1, h, x);
}
}
2 IS AVAILABLE AT = 12
5 IS AVAILABLE AT = 43
2 IS AVAILABLE AT = 410236578
10 IS AVAILABLE AT =
I think this is still providing the results in O(logn) complexity.
A Hashmap might work, if you're not required to use a binary search.
Create a HashMap where the Key is the value itself, and then value is an array of indices where that value is in the array. Loop through your array, updating each array in the HashMap for each value.
Lookup time for the indices for each value will be ~ O(1), and creating the map itself will be ~ O(n).
Find_Key(int arr[], int size, int key){
int begin = 0;
int end = size - 1;
int mid = end / 2;
int res = INT_MIN;
while (begin != mid)
{
if (arr[mid] < key)
begin = mid;
else
{
end = mid;
if(arr[mid] == key)
res = mid;
}
mid = (end + begin )/2;
}
return res;
}
Assuming the array of ints is in ascending sorted order; Returns the index of the first index of key occurrence or INT_MIN. Runs in O(lg n).
It is using Modified Binary Search. It will be O(LogN). Space complexity will be O(1).
We are calling BinarySearchModified two times. One for finding start index of element and another for finding end index of element.
private static int BinarySearchModified(int[] input, double toSearch)
{
int start = 0;
int end = input.Length - 1;
while (start <= end)
{
int mid = start + (end - start)/2;
if (toSearch < input[mid]) end = mid - 1;
else start = mid + 1;
}
return start;
}
public static Result GetRange(int[] input, int toSearch)
{
if (input == null) return new Result(-1, -1);
int low = BinarySearchModified(input, toSearch - 0.5);
if ((low >= input.Length) || (input[low] != toSearch)) return new Result(-1, -1);
int high = BinarySearchModified(input, toSearch + 0.5);
return new Result(low, high - 1);
}
public struct Result
{
public int LowIndex;
public int HighIndex;
public Result(int low, int high)
{
LowIndex = low;
HighIndex = high;
}
}
public void printCopies(int[] array)
{
HashMap<Integer, Integer> memberMap = new HashMap<Integer, Integer>();
for(int i = 0; i < array.size; i++)
if(!memberMap.contains(array[i]))
memberMap.put(array[i], 1);
else
{
int temp = memberMap.get(array[i]); //get the number of occurances
memberMap.put(array[i], ++temp); //increment his occurance
}
//check keys which occured more than once
//dump them in a ArrayList
//return this ArrayList
}
Alternatevely, instead of counting the number of occurances, you can put their indices in a arraylist and put that in the map instead of the count.
HashMap<Integer, ArrayList<Integer>>
//the integer is the value, the arraylist a list of their indices
public void printCopies(int[] array)
{
HashMap<Integer, ArrayList<Integer>> memberMap = new HashMap<Integer, ArrayList<Integer>>();
for(int i = 0; i < array.size; i++)
if(!memberMap.contains(array[i]))
{
ArrayList temp = new ArrayList();
temp.add(i);
memberMap.put(array[i], temp);
}
else
{
ArrayList temp = memberMap.get(array[i]); //get the lsit of indices
temp.add(i);
memberMap.put(array[i], temp); //update the index list
}
//check keys which return lists with length > 1
//handle the result any way you want
}
heh, i guess this will have to be posted.
int predefinedDuplicate = //value here;
int index = Arrays.binarySearch(array, predefinedDuplicate);
int leftIndex, rightIndex;
//search left
for(leftIndex = index; array[leftIndex] == array[index]; leftIndex--); //let it run thru it
//leftIndex is now the first different element to the left of this duplicate number string
for(rightIndex = index; array[rightIndex] == array[index]; rightIndex++); //let it run thru it
//right index contains the first different element to the right of the string
//you can arraycopy this [leftIndex+1, rightIndex-1] string or just print it
for(int i = leftIndex+1; i<rightIndex; i++)
System.out.println(array[i] + "\t");

Categories

Resources