Data Structures and Algos problem -4

Question

Given the set of Arrays (Asked in Amazon)

int [] a= {0,0,-5,30212};
int [] b= {-10,40,-3,9};

we need the sum of elements from the arrays to be -8

the time complexity must less than O(n*2)

Answer

Here given that we have two arrays and we need to find two elements from the array that is one from each in a way that sum comes out to be -8

so here we need to solve the problem in the one go boom not taking any extra loops or anything as we need to solve them in an optimize way but can take some more extra space complexity

let do it

  • We would minus the each element from the array a  with -8 and prepare a list with the compliments and 
  • compare the item of the compliment with the array bas compliment array is -8-0,-8-0,-8-(-5),-8-(30212)
  • So the compliment array would be (-8,-8,-3,-30220)
  • And array b is {-10,40,-3,9}; so yeah -3 of the compliment array is present in the b is the answer
So its solved orally lets have the code below 

  int [] a= {0,0,-5,30212};
        int [] b= {-10,40,-3,9};
        
        int v=-8;
        
        List<Integer> lst= new ArrayList<>();
        
        for(int i=0;i<a.length;i++) {
            lst.add(v-a[i]);
        }
        System.out.println(lst);
        
        for(int i=0;i<b.length;i++) {
            if(lst.contains(b[i])) {
                System.out.println(b[i]);
                break;
            }
        }
    
    }
Do comment if you have any other solution for it I will also add the solution in the post if it would be feasible and correct thanks..!!

Comments

Popular posts from this blog

State space search / blocks world problem by heuristic approach /TIC TAC TOE

Navigation in Vaadin.

Drag and drop items from one Grid to another