Array of Doubled Pair Problem in JavaIt is a problem frequently asked in interviews of top IT companies like Google, Amazon, TCS, Accenture, etc. By solving the problem, one wants to check the logical ability, critical thinking, and problem-solving skill of the interviewee. So, in this section, we are going to solve an array of doubled pair problem in Java with different approaches and logic. Also, we will create Java programs for the same. Problem StatementIn this problem, we have given an integer array (arr[]) of even length. In the array, we have to check if it is possible to reorder the array that must satisfy the following condition: For every 0 < = I < len(arr)/2 If the above conditions satisfy, return true, else return false. Example 1: Input: a[] = [1, 2, 3, 4, 5, 6, 7] Output: false Example 2: Input: a[] = [1, 4, 8, 12, 14, 18] Output: false Example 3: Input: a[] = [4, -2, 2, -4] Output: true Explanation: We can take two groups, [-2, -4] and [2, 4] to form [-2, -4, 2, 4] or [2, 4, -2, -4]. Let's understand the problem in an easy way. Suppose, x is an array element with the least absolute value, there must exist a pair with the element 2*x, as there does not exist any other element x/2 to pair with it. Let's check elements in order of absolute value. When we check an element x and it isn't used, it must pair with 2*x. We will try to write x, 2x. If we fail to do so, then return false. If we write everything, then return true. In order to track what we have not written yet, use a count variable to store it. Let's understand it through examples. ExampleCase 1: If an array has positive elements Consider an array [2, 4, 4, 8]. We have one x = 2, we need to match it with one 2x = 4. Then one 4 is gone, and we have the other x = 4. We need to match it with one 2x = 8. There are no other elements to match. In this array, we have picked the first element of the array because it's the smallest element of the array and there is no x/2 left. So, we need to find 2x. Case 2: If an array has negative elements One way is that start from the biggest element (with absolute value smallest), and we apply the same logic (as above). Another way is, start from the smallest element (with absolute value biggest), and try to find x/2 each turn. Explanation
Here, we need not to care about 0's. It does not fit in the above logic but it will not break the algorithm.
Algorithm
Java Program to Check Array of Doubled PairDoubledPair1.java Output: false Let's see another logic for the same. DoubledPair2.java Output: true Complexity AnalysisThe runtime is O(N * logN), constructing the tree map is the dominant part of the runtime. Next TopicTag Content Extractor Problem in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India