
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if array can be divided into two sub-arrays such that their absolute difference is Ks in Python
In this article we are going to check whether the given array can be divided into two sub-array in such a way that the absolute difference between the sums of these two sub-array is equal to the given value k.
The absolute difference is nothing but the non-negative gap between two numbers, calculated as abs(sum1-sum2). In this task the split must produce two non-empty sub-array i.e. at least one element should be present in each part.
Example scenarios
Following are the example scenarios:
Scenario 1Input: array = [3, 1, 4, 2, 2], K = 4 Output: YES Explanation: In the given array, the possible split is: Left sub-array = [3, 1] -> sum = 4 Right sub-array = [4, 2, 2] -> sum = 8 The Absolute difference = |4 - 8| = 4, which matches K. Hence, the answer is YES.Scenario 2
Input: array = [3, 1, 4, 2, 2], K = 2 Output: NO Explanation: In the given array checking all possible splits: [3] and [1, 4, 2, 2] -> difference = 6 [3, 1] and [4, 2, 2] -> difference = 4 [3, 1, 4] and [2, 2] -> difference = 4 [3, 1, 4, 2] and [2] -> difference = 8 None of these differences equal K = 2, so the answer is NO.
Let's dive into the following example, for getting better understanding on checking whether the given array can be divided into two sub arrays such that the absolute difference is equal to k.
Algorithm to Solve the Problem
- Step 1 ? At the start, we will calculate the total sum of the array (x).
- Step 2 ? Then, traverse through the array, maintaining a running left sum.
- Step 3 ? At each point: Calculate right_sum(z)=total_sum(x)-left_sum(y), then check if abs(left_sum - right_sum) ==k
- Step 4 ? If the condition is satisfied, return yes; otherwise false.
Program Implementation
Let's look at the following example, where we are going to swap 3,2 from the given array [1,3,2,4,5], which makes it sorted with one swap.
def demo(array, K): x = sum(array) y = 0 for i in range(len(array) - 1): y += array[i] z = x - y if abs(y - z) == K: return True return False array1 = [5, 1, 2, 2] K1 = 0 print("YES" if demo(array1, K1) else "NO") array2 = [3, 1, 4, 2, 2] K2 = 2 print("YES" if demo(array2, K2) else "NO")
Following is the output of the above program:
YES NO