Given three positive integers A, B and N, the task is to split N into two parts such that they become equal i.e. find two positive integers X and Y, such that X + Y = N and A + X = B + Y. If no such pair exists, print -1.
Input: A = 1, B = 3, N = 4
Output: 3 1
Explanation: If X = 3 and Y = 1, then A + X = B + Y and X + Y =4
Input: A = 1, B = 3, N = 1
The simplest approach to solve this problem is to generate all possible pairs with sum N and check for each pair, if A + X = B + Y.
Time complexity: O(N2)
Auxiliary Space: O(1)
It can be observed that, since X + Y = N and A + X = B + Y, then X can be expressed as (N + B – A) / 2. Simply check if (N + B – A) / 2 is even or not. If it is even, calculate X and corresponding Y. Otherwise, print -1.
Below is the implementation of the above approach:
Time Complexity: O(1)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Count all subarrays whose sum can be split as difference of squares of two Integers
- Find the element whose multiplication with -1 makes array sum 0
- Split an Array A into Subsets having equal Sum and sizes equal to elements of Array B
- Split an array into two equal Sum subarrays
- Split array into two subsequences having minimum count of pairs with sum equal to X
- Split numbers from 1 to N into two equal sum subsets
- Split array into two equal length subsets such that all repetitions of a number lies in a single subset
- Find a pair of elements swapping which makes sum of two arrays same
- Find side of Square which makes minimal area to fit two identical rectangles inside it
- Minimize subset addition or multiplication to make two given triplets equal
- Partition an array of non-negative integers into two subsets such that average of both the subsets is equal
- Minimum number of integers required such that each Segment contains at least one of them
- Derive a MultiSet from given Array such that sum is > P and removing any element makes sum < P
- Count numbers < = N whose difference with the count of primes upto them is > = K
- Count of numbers whose difference with Fibonacci count upto them is atleast K
- Split N^2 numbers into N groups of equal sum
- Split the array into equal sum parts according to given conditions
- Check if an array can be split into 3 subsequences of equal sum or not
- Count ways to split a Binary String into three substrings having equal count of zeros
- Find the Minimum length Unsorted Subarray, sorting which makes the complete array sorted
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.