The Wayback Machine - https://web.archive.org/web/20220308222656/https://www.geeksforgeeks.org/check-if-there-exists-a-non-adjacent-pair-with-given-sum/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Check if there exists a non adjacent pair with given sum

  • Last Updated : 08 Mar, 2022

Given an array nums[ ] and an integer target. Find whether there exists a combination of integers in nums[ ] such that their sum is equal to target and none of those elements are adjacent in the original array.

Example :

Input : nums[ ] = [1, 2, 2, 3],  target = 4
Output : true
Explanation : We can pick [1, 3] since they are non-adjacent and sums to 4

Input : nums[ ] = [1, 3, 1], target = 4
Output: false
Explanation : We can’t pick [1, 3] or [3, 1] since they are adjacent.

 

Approach: The problem can be solved using Dynamic Programming as per below steps:

  • dp[i][j]: Create a 2-d dp array that stores if it is possible to achieve a sum of exactly j after considering the first i elements from the array.
  • At a given index i and a given sum j there can be two cases:
    • Either we can include the current number, nums[i], or we don’t. 
    • If we don’t include the current number, we simply look back to the previous row of the dp. 
    • If we do include the current number, we have to look back two rows in the dp array, because no adjacent elements can be selected. 
    • So once we select element i we can ignore element i-1 since it can’t be taken.
  • Base Case: 
    • Initially intialize the boolean dp table with false. 
    • Then, fill true in first column as sum 0 can always be achieved by not taking any element. 
    • Also fill dp[i][nums[i]] with true values, which indicates that we can achieve a sum of nums[i] after considering the first i elements from the array (which is obvious just take the element at index i).
  • Transistion states:
    • Case 1: dp[i][j] = dp[i – 1][j] || dp[i][j]  
      • check the value at previous row 
      • if it is true then we can make the subset sum equal to target by taking elements till the last row,  
      • So make dp[i][j] true as well
    • Case 2: dp[i][j] = dp[i – 2][j – nums[i]] || dp[i][j] 
      • check if we add the current element nums[i] to the current row – 2 (as it is not adjacent) dp table and make the sum equal to target.

Illustration:

Consider the example where nums[ ] = [1, 2, 2, 3], target = 4

The dp table would look like the following (i represents nums[i] and j represent target)

i (nums[i]) \ j (target)01234
0 (nums[0]=1)truetruefalsefalsefalse
1 (nums[1]=2)truetruetruefalsefalse
2 (nums[2]=2)truetruetruetruefalse
3 (nums[2]=3)truetruetruetruetrue

Below is the implementation of the above approach:

C++




// C++ program to implement above approach
  
#include <bits/stdc++.h>
using namespace std;
  
bool subsetSumNonAdjacent(
    vector<int>& nums, int target)
{
    // size of the array
    int n = nums.size();
  
    // Boolean dp table fill with false
    vector<vector<bool> > dp(
        n, vector<bool>(target + 1, false));
  
    // Base Case
    // Initialize dp[i][0]= true
    // as 0 can always be achieved
    // by not taking anything
    for (int i = 0; i < n; i++) {
        dp[i][0] = true;
    }
  
    // Initialize dp[i][nums[i]]= true
    // as nums[i] can always be achieved
    // by taking only element
    // at index i that is nums[i]
    for (int i = 0; i < n; i++) {
        dp[i][nums[i]] = true;
    }
  
    for (int i = 0; i < n; i++) {
        for (int j = 0; j <= target; j++) {
  
            // check if we can take previous row
            if (i - 1 >= 0) {
                dp[i][j]
                    = dp[i - 1][j] || dp[i][j];
            }
  
            // check for row-2
            if (i - 2 >= 0 && j >= nums[i]) {
                dp[i][j]
                    = dp[i - 2][j - nums[i]]
                      || dp[i][j];
            }
        }
    }
  
    return dp[n - 1][target];
}
  
// Driver code
int main()
{
    vector<int> nums = { 1, 2, 2, 3 };
    int target = 4;
    cout << boolalpha
         << subsetSumNonAdjacent(nums, target);
    return 0;
}
Output
true

Time Complexity: O(N*target)
Auxiliary Space: O(N*target)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!