Question: Given an array of n elements. Find two elements such that their sum is equal to a given element ‘K’ ?

    Input: arr [] = {42, 23, 15, 16, 8, 4} and element K = 58
    Output: 16, 42

    We discussed the approach to this problem using 2 loops in this post. But obviously this was not a good approach as it had a time complexity of O(n2). The time taken to solve such a problem if the array has elements in range of million will be very high. We need to optimize this approach.

    The steps involved in this algorithm will be:-

    • Sort the array. This operation takes a time of O(nlog(n))
    • Now maintain a variable lowIndex = 0 and highIndex = size-1.
    • Compute sum = arr[lowIndex] + arr[highIndex].
    • If (sum == K), then simply return the two variable.
    • If (sum < K), that means we need to add a bigger element to the sum, which can be obtained if we increment lowIndex, so
      if(sum<K)
          lowIndex++;
      
    • If (sum>K), that means we need to add a smaller number, the smaller number can be found if we decrement highIndex, so
      if(sum>;K)
          highIndex--;
      
    • We can repeat this process until we find the two digits. Else we return that no elements are found.

    Here is an implementation of the above algorithm.

    void twoElementsSumK(int arr[], int size, int K)
    {
    	//first sort the array
    	quickSort(arr,size);
    
    	//maintain the low and high index
    	int lowIndex = 0;
    	int highIndex = size-1;
    
    	while(lowIndex < highIndex)
    	{
    		//get the sum
    		int temp = arr[lowIndex] + arr[highIndex];
    
    		//return if we find a match
    		if(temp == K)
    		{
    			printf("The elements are :- %d %d",arr[lowIndex],arr[highIndex]);
    			return;
    		}
    
    		//to change the low and high index
    		if(temp < K)
    			lowIndex++;
    		else
    			highIndex--;
    	}
    }
    

    Time Complexity:- O(nlog(n))
    Space Complexity:- O(1)

    You can download the working example of code from here. Use your favorite text editor to open it (Notepad++, vim, gedit)

     

    Method 3 – Use a hash table

    We can also solve this problem using a hash table. Since out objective is to find two indexes of the array whose sum is K. Let us say those indexes are X and Y. That means arr[X] + arr[Y] = K.

    What we need is, for each element of the input array arr[X], check whether K – arr[X] also exists in the input array. Now, let us simplify that searching with a hash table.

    Algorithm:

    • For each element of the input array, insert into the hash table. Let us say the current element is arr[X].
    • Before proceeding to the next element we check whether K – arr[X] also exists in the hash table or not.
    • Existence of such number indicates that we are able to find the indexes.
    • Otherwise, proceed to the next input element.

    Time Complexity:- O(n), considering the fact that searching in hash table takes time O(1).
    Space Complexity:- O(n), to create and maintain the hash table.

    0 comments
    0 FacebookTwitterLinkedinWhatsappEmail
  • Question: Given an array of n elements. Find two elements such that their sum is equal to a given element ‘K’ ? Input: arr [] = {42, 23, 15, 16, 8, 4} and element K = 58 Output: 16, 42 To understand the problem statement a little more, we are given with an array of ‘n’ elements and another element ‘K’. We need to find if there exists 2 elements in the given array such that their sum equals the given element K. The array is not sorted. One simple …

    0 FacebookTwitterLinkedinWhatsappEmail
  • Question: Given an array with n+2 elements, all elements of the array are in range 1 to n and also all elements occur only once except 2 numbers which occur twice. Find those 2 repeating numbers. Input: arr[] = {6, 2, 6, 5, 2, 3, 1} Output: 6 2 We discussed a method to perform this task using an extra array to count the occurrences of elements, but this approach took an extra space of the range of elements of array. If we have a very wide range, then we …

    0 FacebookTwitterLinkedinWhatsappEmail
  • Question: Given an array with n+2 elements, all elements of the array are in range 1 to n and also all elements occur only once except 2 numbers which occur twice. Find those 2 repeating numbers. Input: arr [ ] = {6, 2, 6, 5, 2, 3, 1} Output: 6 2 We discussed the method to find the 2 repeating element using 2 loops, but that method had a great time complexity and it was not at all an optimal solution. We can optimize it using a count array. This …

    0 FacebookTwitterLinkedinWhatsappEmail
  • Question: Given an array with n+2 elements, all elements of the array are in range 1 to n and also all elements occur only once except 2 numbers which occur twice. Find those 2 repeating numbers. Input: arr[] = {6, 2, 6, 5, 2, 3, 1} Output: 6 2 One simple way is to scan the complete array for each element of the input elements. That means use two loops. In the outer loop, select elements one by one and count the number of occurrences of the selected element in …

    0 FacebookTwitterLinkedinWhatsappEmail
  • Question: Given an array of positive integers, all numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time and constant space. Input:- arr[] = {1, 2, 3, 2, 3, 1, 3} Output:- 3 This is a very simple problem. The basic and naive approach will be to scan the complete array and keep a track of each element. We need to count the occurrence of each element and see if its even or odd. This would be a very …

    0 FacebookTwitterLinkedinWhatsappEmail
  • Question: Write a program to rotate an array arr[], having a size ‘n’ by ‘d’ elements? Input: arr[] = { 4, 8, 15, 16, 23, 42, 99 }, d = 3 Output: 16, 23, 42, 99, 4, 8, 15 Let us suppose our array is in this way: On rotating the array by 3 elements, it should look like: We can do this by rotating the array one element at a time. We discussed it in this post. We can also use the REVERSAL Algorithm to rotate the array. This …

    0 FacebookTwitterLinkedinWhatsappEmail

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More