What will be the best solution to this question? (Less than O(n))
Given an array of positive integers where successive elements increase by 1
(except for a single element that does NOT increase by one--the start of the
"corruption"), return the index of where the corruption starts.
Example 1:
array: [5, 6, 7, 8, 12, 13] indices: 0 1 2 3 4 5
The corruption starts at index 4.
Example 2:
array: [5, 2, 3, 4, 5, 6] indices: 0 1 2 3 4 5
The corruption starts at index 1.
P.S. My solution was of O(n), also I tried to branch it in two parts still it will reduce half.
Hint: I was told I can use binary search.
Edit:
My solution was simply to iterate the array and see if difference is greater or less than one.
Try something like this
public class Main {
public static void main(String[] args) {
int[] nums = {5, 6, 7, 8, 12, 13};
int res = checkArray(nums, 0, nums.length - 1);
System.out.println("res = " + res);
}
public static int checkArray(int[] nums, int start, int end) {
if (end - start < 2) {
return end;
} else {
int middle = (start + end) / 2;
int a = nums[start];
int b = nums[middle];
if (b - a != middle - start) {
return checkArray(nums, start, middle);
} else {
return checkArray(nums, middle, end);
}
}
}
}
It use the fact that difference between first and last element of subarray is equal to its length if array do not have corruption.
public static void main(String[] args) {
// corruption starts at 13
int[] arr = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 17};
int corruptionIndex = -1;
int start = 0;
int end = arr.length;
while (end - start > 1) {
int middle = (start + end) / 2;
// we add the first element onto our value as an offset
int expectedValue = middle + arr[0];
if (arr[middle] != expectedValue) {
// something has already gone wrong, let's check the first half
end = middle;
}
else {
// so far so good, let's check the second half
start = middle;
}
corruptionIndex = end;
}
System.out.println("Corruption Index: " + corruptionIndex);
}
var arr1 = [5, 9, 7, 8, 9, 13] ;
var arr2 = [5, 2] ;
var arr3 = [5, 6, 7, 8, 9, 13] ;
check(arr1);
check(arr2);
check(arr3);
function check(arr){
for(var i=1;i<arr.length;i++){
if(arr[i]-arr[i-1] !=1 ){
console.log('corroption begins at '+i);
break;
}
}
}
we can check for current and prev element difference , right. if diff is not 1, we need to break. its in js
O(n) is your only option. Binary search is O(log(n)) but that only works for searching for a specific number in a sorted list. You neither have a sorted list nor a specific number you are searching for
class FindCorruptionIndex
{
public static void main(String[] args)
{
int i,j;
int array[]={1,2,3,4,7,8,9};
System.out.print("The array is [ ");
for (int x :array )
{
System.out.print(x+",");
}
System.out.print("\b ] ");
System.out.println();
for(i=0;i<array.length-1;i++)
{
j=array[i+1]-array[i];
if (j>=2)
{
System.out.println("The corruption Index position is "+(i+1));
}
}
}
}
Related
Given two arrays which represents a path and each element in the array represent the time it takes the driver to travel, write a method that chooses the fastest path he can take. The driver can switch paths only once between arrays.
For example the following arrays:
int[] road1 = new int[] { 5, 4, 5, 8, 12, 9, 9, 3 };
int[] road2 = new int[] { 7, 3, 3, 12, 10, 2, 10, 7 };
the output should be 49 since the driver will start at road2 and switch at index 6 to the second Array.
Edit:
My question is how do I make the recursion stop after switching to the other array? I tried to put a counter marker but it didn't work and I reverted back to my original output. Am I missing something about how recursion works?
My code prints 53 where it should print 49.
My code:
public class MyClass {
public static int shortestRoad(int[] road1, int[] road2) {
return shortestRoadNumbers(road1, road2, 0);
}
private static int shortestRoadNumbers(int[] road1, int[] road2, int index) {
if (index == road1.length || index == road2.length) {
return 0;
}
if (road1[index] >= road2[index] && road1[index + 2] >= road2[index + 2]) {
return (road2[index] + shortestRoadNumbers(road1, road2, index + 1));
} else {
return (road1[index] + shortestRoadNumbers(road1, road2, index + 1));
}
}
public static void main(String args[]) {
int[] road1 = new int[] { 5, 4, 5, 8, 12, 9, 9, 3 };
int[] road2 = new int[] { 7, 3, 3, 12, 10, 2, 10, 7 };
MyClass.shortestRoad(road1, road2);
int result = MyClass.shortestRoad(road1, road2);
System.out.println(result);
}
}
Let the following schema to illustrate your problem
We have two paths, and each path contain many nodes (values) , we can switch from one path to another just one time. Find the best combination of nodes (values) that minimise the score.
We can distinguish 4 cases:
1- the sum of the values of the first path without switching.
2-the sum of the values of the second path without switching.
3-the sum of the values from the first path until a node i, then switch to path second path from node i+1 (sum from node+1 til the end)
4-the inverse of the point 3.
static int shortestRoad(int road1[], int road2[])
{
// case 1
int bestValue = sumValues(road1,0);
// case 2
int sumValuesRoad2 = sumValues(road2,0);
if ( sumValuesRoad2 < bestValue)
bestValue = sumValuesRoad2;
// case 3: best values of all combination from road 1 to road 2
int bestValuesSwitchFromRoad1ToRoad2 = shortestRoad_Switch_RoadFrom_RoadTo(road1, road2);
if ( bestValuesSwitchFromRoad1ToRoad2 < bestValue)
bestValue = bestValuesSwitchFromRoad1ToRoad2;
// case 4: best values of all combination from road 2 to road 1
int bestValuesSwitchFromRoad2ToRoad1 = shortestRoad_Switch_RoadFrom_RoadTo(road2, road1);
if ( bestValuesSwitchFromRoad2ToRoad1 < bestValue)
bestValue = bestValuesSwitchFromRoad2ToRoad1;
return bestValue;
}
sum the values of a given array from idx til the end:
static int sumValues(int array[], int idx_from)
{
int sum = 0;
for (int i = idx_from; i<array.length; ++i)
sum += array[i];
return sum;
}
case 3 and 4:
static int shortestRoad_Switch_RoadFrom_RoadTo(int[] road_from, int[] road_to)
{
int sumValues_RoadFrom_til_idx = 0;
int sumValues_RoadFrom_idx_switch_RoadTo = 0;
int bestValue = Integer.MAX_VALUE;
for (int i = 0; i<road_from.length-1; ++i)
{
sumValues_RoadFrom_til_idx += road_from[i];
sumValues_RoadFrom_idx_switch_RoadTo = sumValues_RoadFrom_til_idx+sumValues(road_to,i+1);
if(sumValues_RoadFrom_idx_switch_RoadTo < bestValue )
bestValue = sumValues_RoadFrom_idx_switch_RoadTo;
}
return bestValue;
}
Driver code:
public static void main(String[] args)
{
int road1[] = { 5, 4, 5, 8, 12, 9, 9, 3 };
int road2[] = { 7, 3, 3, 12, 10, 2, 10, 7 };
int road_a[] = { 1, 1, 1, 1, 1, 9, 9, 9,9,9 };
int road_b[] = { 9, 9, 9, 9, 9, 1, 1, 1,1,1 };
int road_c[] = { 1, 1, 1, 1, 1, 2 };
int road_d[] = { 9, 9, 9, 9, 9, 1, 1, 1,1,1 };
System.out.println("best road1, road2 = "+shortestRoad(road1,road2));
System.out.println("best road_a, road_b = "+shortestRoad(road_a,road_b));
System.out.println("best road_c, road_d = "+shortestRoad(road_c,road_d));
return 0;
}
Results:
best road1, road2 = 49
best road_a, road_b = 10
best road_c, road_d = 7
ps:
the best path in your example is begin from road2 and then switch to road 1 at i=5 (i begin from 0)
{ 5, 4, 5, 8, 12, 9, -->9, 3 }
{ -->7, 3, 3, 12, 10, 2 /, 10, 7 }
public static int shortestRoad(int[]road1, int[]road2)
{
int sumRoad1Only = 0;
int sumRoad2Only = 0;
for(int i=0; i<road1.length; i++)
{
sumRoad1Only += road1[i];
sumRoad2Only += road2[i];
}
Those sums are for the option that the driver chooses one lane, and doesn't change it until the end. Now, we can find the switch index, for options like starting at one road, and switching to the other. In this specific question I realized that the best point of switch between the arrays - is where the difference between the two collected sums until a certain index is the largest. In your example, it is index 6. That doesn't say that switching a lane is always giving a smaller sum.
int roadIndex1 = road1.length-1;
int roadIndex2 = road2.length-1;
int totalSumRoad1 = sumRoad1Only;
int totalSumRoad2 = sumRoad2Only;
int max = 0;
int indexOfSwitch = 0;
int diff = 0;
while(roadIndex1 >=0 && roadIndex2 >=0)
{
diff = Math.abs(totalSumRoad2 - totalSumRoad1);
if(diff > max)
{
max = diff;
indexOfSwitch = roadIndex1;
}
totalSumRoad1 -= road1[roadIndex1];
totalSumRoad2 -= road2[roadIndex2];
roadIndex1--;
roadIndex2--;
}
If the index of switch is at last index, we shall move it one left, so there be a transition between the arrays.
if(indexOfSwitch == road1.length-1)
{
indexOfSwitch--;
}
now we found the indexOfSwitch, we can calculate the options of starting at road1, and switching exactly once to road2, and vice versa:
int begin1 = 0;
int begin2 = 0;
for(int k = 0; k<=indexOfSwitch; k++)
{
begin1 += road1[k];
begin2 += road2[k];
}
int end1 = sumRoad1Only - begin1;
int end2 = sumRoad2Only - begin2;
int begin1End2 = begin1 + end2;
int begin2End1 = begin2 + end1;
and when we find all the options, we can return the minimum.
return Math.min(Math.min(sumRoad1Only, sumRoad2Only), Math.min(begin1End2, begin2End1));
I want to make a function that takes as parameters an array and a boolean. The boolean tells the function if the rest of the division of the array is to be included. It then returns a new array which is the copy of the second half of the first:
secondHalf({1, 2, 3, 4, 5}, true) → {3, 4, 5}
secondHalf({1, 2, 3, 4, 5}, false) → {4, 5}
For this assignment, I'm not supposed to use any other classes.
Here's what I've attempted:
static int[] secondHalf(int[] vector, boolean include) {
int size = vector.length/2;
if(vector.length%2 == 0)
include = false;
if(include)
size ++;
int[] vector_2 = new int[size];
int i = 0;
while(i < size){
if(include)
vector_2[i] = vector[i+size-1];
vector_2[i] = vector[i+size+1];
i++;
}
return vector_2;
To find the size of vector_2, I've decided to use compound assignment operators. So the first part of this solution checks for the required condition and assigns a value to size in a single statement.
Since we know how many times to iterate over the loop, I think a for loop would be more appropriate than a while loop.
The loop retrieves all the values in vector from the middle of the array to the end of the array and places each value into vector_2.
static int[] secondHalf(int[] vector, boolean include) {
int size = vector.length/2 + (include && vector.length%2 != 0 ? 1 : 0);
int[] vector_2 = new int[size];
for(int i = 0; i < size; i++)
vector_2[i] = vector[vector.length - size + i];
return vector_2;
}
People have hinted at System#arraycopy, but with Arrays.copyOfRange there is an even simpler method, where you only have to define the proper start index and directly receive the copy.
The start index is array.length / 2 by default. Iff the include flag is true, then you have to add the remainder of dividing the array length by 2 to that.
An MCVE:
import java.util.Arrays;
public class ArrayPartCopy
{
public static void main(String[] args)
{
int array0[] = { 1, 2, 3, 4, 5 };
System.out.println("For " + Arrays.toString(array0));
System.out.println(Arrays.toString(secondHalf(array0, true)));
System.out.println(Arrays.toString(secondHalf(array0, false)));
int array1[] = { 1, 2, 3, 4 };
System.out.println("For " + Arrays.toString(array1));
System.out.println(Arrays.toString(secondHalf(array1, true)));
System.out.println(Arrays.toString(secondHalf(array1, false)));
}
static int[] secondHalf(int[] array, boolean include)
{
int start = array.length / 2;
if (include)
{
start += array.length % 2;
}
return Arrays.copyOfRange(array, start, array.length);
}
}
The output is
For [1, 2, 3, 4, 5]
[4, 5]
[3, 4, 5]
For [1, 2, 3, 4]
[3, 4]
[3, 4]
I am a newbie to programming. I am trying to create a program that would display an array in reverse. Plus also find the even and odd numbers of an array,sum the count and also display the even and odd numbers. The code works but the problem is that it also reverses the even and odd arrays and it shows this weird zero in those arrays. What am I doing wrong?
Please also provide explanation. Thanks!
import java.util.Arrays;
public class ArrayTest {
public static void main(String[] args)
{
int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13};
for ( int i=0; i<array.length/2; i++ )
{
int temp = array[i];
array[i] = array[array.length-(1+i)];
array[array.length-(1+i)] = temp;
}
System.out.println("Array after reverse: \n" + Arrays.toString(array));
int even=0;
int odd=0;
int[] Even = new int[13];
int[] Odd = new int[13];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[i] = array[i];
even++;
}
else
{
Odd[i] = array[i];
odd++;
}
}
System.out.println("Even: "+even+" ");
System.out.println(Arrays.toString(Even));
System.out.println("Odd: "+odd+" ");
System.out.println(Arrays.toString(Odd));
}
}
The output is:
Array after reverse:
[13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Even: 6
[0, 12, 0, 10, 0, 8, 0, 6, 0, 4, 0, 2, 0]
Odd: 7
[13, 0, 11, 0, 9, 0, 7, 0, 5, 0, 3, 0, 1]
You need to correct your logic
int[] Even = new int[(array.length/2)+1];
int[] Odd = new int[(array.length/2)+1];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[even] = array[i];
even++;
}
else
{
Odd[odd] = array[i];
odd++;
}
}
As per you code, you are initializing array of size 13 for odd and even, which is not correct.
int[] Even = new int[13];
int[] Odd = new int[13];
So, by default, Even and Odd array will be initialized by 0 value. Then, you are setting value as per main array, which a size of 13 on alternate basis (even/odd).
==Updated==
Since, you don't want Even and Odd array in reverse order. Then, you can move the code up.
>>Demo<<
You faced 2 problems (I guess so)
The odd and even arrays are also in reverse order
Reason: The first For loop reverses the 'array' and stores the results in array itself. So, the next time when you try working with 'array' to find odd/even numbers, you are actually working with the reversed array.
Solution: You can assign the original array to a backup array and use that backup array to find odd and even nos.
Unnecessary zeros:
Reason: In your second for loop you used odd[i]=array[i] which seems to be a logical error in your code. Consider the case:
value of i : 0 1 2 3 4 5 ... 12
value of array[i]: 1 2 3 4 5 6 ... 13
value of odd[i] : 1 0 3 0 5 0 ... 13
value of even[i] : 0 2 0 4 0 6 ... 0
This means, the control inside for loop is made to flow either to if{} block or the else{} block and not the both. So, when if(condition) is satisfied, then even[i] array will be updated. But meanwhile what happens to the odd[i] array? It retains the inital value '0'. That's it!
I hope the following code helps you:
import java.util.Arrays;
public class A
{
public static void main(String[] args)
{
int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13};
int[] arr2 = new int[array.length]; // backup array
arr2=Arrays.copyOfRange(array,0,array.length);
for ( int i=0; i<arr2.length/2; i++ )
{
int temp = arr2[i];
arr2[i] = arr2[arr2.length-(1+i)];
arr2[arr2.length-(1+i)] = temp;
}
System.out.println("Array after reverse: \n" + Arrays.toString(arr2));
int even=0;
int odd=0;
int[] Even = new int[13];
int[] Odd = new int[13];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[even] = array[i];
even++;
}
else
{
Odd[odd] = array[i];
odd++;
}
}
Even=Arrays.copyOfRange(Even,0,even);
Odd=Arrays.copyOfRange(Odd,0,odd);
System.out.println("Even: "+even+" ");
System.out.println(Arrays.toString(Even));
System.out.println("Odd: "+odd+" ");
System.out.println(Arrays.toString(Odd));
}
}
Note: I have used Arrays.copyOfRange(array,start,end) function to copy a certain part of the array from start to end-1 position.
Output:
Array after reverse:
[13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Even: 6
[2, 4, 6, 8, 10, 12]
Odd: 7
[1, 3, 5, 7, 9, 11, 13]
Hope this helps :)
--Mathan Madhav
You select even and odd numbers from reversed array.
You use wrong index for even and odd arrays.
If you don't want to see zeros in output, use print in for statement. Another solution - firstly count odd and even numbers and create arrays with exact size.
import java.util.Arrays;
public class ArrayTest {
public static void main(String[] args)
{
int[] array = {1,2,3,4,5,6,7,8,9,10,11,12,13};
int even=0;
int odd=0;
int[] Even = new int[13];
int[] Odd = new int[13];
for ( int i=0; i<array.length; i++)
{
if (array[i] % 2 == 0)
{
Even[even++] = array[i];
}
else
{
Odd[odd++] = array[i];
}
}
for ( int i=0; i<array.length/2; i++ )
{
int temp = array[i];
array[i] = array[array.length-(1+i)];
array[array.length-(1+i)] = temp;
}
System.out.println("Array after reverse: \n" + Arrays.toString(array));
System.out.println("Even: "+even+" ");
System.out.println(Arrays.toString(Even));
System.out.println("Odd: "+odd+" ");
System.out.println(Arrays.toString(Odd));
}
}
This question already has answers here:
Find the Smallest Integer Not in a List
(28 answers)
Closed 8 years ago.
This is an interview question, but I couldn't solve it in time, so posting it here:
Given a sorted array of n integers where each integer is in the range from 0 to m-1 and m > n. Find the smallest number that is missing from the array.
Examples
Input: {0, 1, 2, 6, 9}, n = 5,m = 10
Output: 3
Input: {4, 5, 10, 11}, n = 4, m = 12
Output: 0
The code for this is as follows:
int findFirstMissing(int array[], int start, int end) {
if(start > end)
return end + 1;
if (start != array[start])
return start;
int mid = (start + end) / 2;
if (array[mid] > mid)
return findFirstMissing(array, start, mid);
else
return findFirstMissing(array, mid + 1, end);
}
Now, the question is that input array can have duplicates also:
input = [0, 1, 1, 2, 3, 3, 4, 5, 5, 7]
output = 6
How do I solve it efficiently? What kind of optimizations can be applied?
It can be easily proved that you have to this in O(n) time, as you can't distinguish without checking every single value two tables:
1,2,_3_,4,5,7
and
1,2,_2_,4,5,7
This solution works in O(N) time and uses O(1) additional memory:
public class Test {
public static void main(String[] args) {
int m = 5;
int[] data = new int[] {0, 1, 1, 2, 3, 3, 4, 5};
int current = 0;
for (int i = 0; i < data.length; ++i) {
if (current == data[i]) {
current++;
}
}
if (current >= m) {
System.out.println("All is here");
} else {
System.out.println(current);
}
}
}
Note: n is actually ignored, I used data.length instead.
Solution
public static void main(String[] args) {
Collection<Integer> input = new LinkedList<Integer>(Arrays.asList(10, 9, 7, 6, 5, 4, 3, 2, 1));
NavigableSet<Integer> sortedOriginal = new TreeSet<Integer>(input);
NavigableSet<Integer> numbers = new TreeSet<Integer>();
for(int i=sortedOriginal.first();i<=sortedOriginal.last();i++){
numbers.add(i);
}
for(Integer x : numbers){
if(!sortedOriginal.contains(x)){
System.out.println(x);
break;
}
}
}
Hello everyone hoping you can help me here,
My problem is that I need to be able to search through an ArrayList using binary search and find where the correct place to add an object so that the list stays in order. I cannot use the collections sort as this is a homework. I have correctly implemented a boolean method that tells if the list contains an item you want to search for. That code is here:
public static boolean search(ArrayList a, int start, int end, int val){
int middle = (start + end)/2;
if(start == end){
if(a.get(middle) == val){
return true;
}
else{
return false;
}
}
else if(val < a.get(middle)){
return search(a, start, middle - 1, val);
}
else{
return search(a, middle + 1, end, val);
}
}
What I need to do is use this method to see if the number already exists in the list and if that returns false then I need to be able to use another binary search to figure out where in the list the number (val) should go. Any help is greatly appreciated, thank you!!!
Justin
Well instead of returning true or false, you can return the last index in your search. So if the value isn't in the List, then return the last index you visited, and see if the value is less than or larger than the current value at that index, and add the new value accordingly.
Instead of returning boolean value, you should return position of value, which you already found. Recurrent solution is OK, but for really big List it will be a problem to find the result. Instead of using recurrention try to implement loop-based solution. I have created a little demo, which will help you to understand it:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SourceCodeProgram {
private List<Integer> integers = new ArrayList<Integer>();
public static void main(String argv[]) throws Exception {
SourceCodeProgram test = new SourceCodeProgram();
test.addIntegerToSortedListVerbose(10);
test.addIntegerToSortedListVerbose(2);
test.addIntegerToSortedListVerbose(11);
test.addIntegerToSortedListVerbose(-1);
test.addIntegerToSortedListVerbose(7);
test.addIntegerToSortedListVerbose(9);
test.addIntegerToSortedListVerbose(2);
test.addIntegerToSortedListVerbose(5);
test.addIntegerToSortedListVerbose(1);
test.addIntegerToSortedListVerbose(0);
}
private void addIntegerToSortedListVerbose(Integer value) {
int searchResult = binarySearch(integers, value);
System.out.println("Value: " + value + ". Position = " + searchResult);
integers.add(searchResult, value);
System.out.println(Arrays.toString(integers.toArray()));
}
private int binarySearch(List<Integer> list, Integer value) {
int low = 0;
int high = list.size() - 1;
while (low <= high) {
int mid = (low + high) / 2;
Integer midVal = list.get(mid);
int cmp = midVal.compareTo(value);
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid;
}
return low;
}
}
Program prints:
Value: 10. Position = 0
[10]
Value: 2. Position = 0
[2, 10]
Value: 11. Position = 2
[2, 10, 11]
Value: -1. Position = 0
[-1, 2, 10, 11]
Value: 7. Position = 2
[-1, 2, 7, 10, 11]
Value: 9. Position = 3
[-1, 2, 7, 9, 10, 11]
Value: 2. Position = 1
[-1, 2, 2, 7, 9, 10, 11]
Value: 5. Position = 3
[-1, 2, 2, 5, 7, 9, 10, 11]
Value: 1. Position = 1
[-1, 1, 2, 2, 5, 7, 9, 10, 11]
Value: 0. Position = 1
[-1, 0, 1, 2, 2, 5, 7, 9, 10, 11]