VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-k-can-be-obtained-by-performing-arithmetic-operations-on-any-permutation-of-an-array/

⇱ Check if K can be obtained by performing arithmetic operations on any permutation of an Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if K can be obtained by performing arithmetic operations on any permutation of an Array

Last Updated : 15 Jul, 2025

Given an array arr[] of N integers and an integer K, the task is to check if the expression formed for any permutation of the given array after assigning arithmetic operators(+, -, /, *) gives the value K or not. If found to be true, then print the order of operations performed. Otherwise, print "-1".
Note: After division operator '/' is applied, the result can be a floating-point number. 

Examples: 

Input: arr[] = {2, 0, 0, 2}, K = 4
Output: 2 + 0 => 2 + 2 => 4 + 0 => 4

Input: arr[] = {1, 2, 4, 7}, K = 50
Output: -1

Approach: The idea is to use Backtracking and find the value of the resultant equation by generating all possible combinations of assigning the operators. Below are the steps: 

  1. Traverse the array And choose the first two elements and apply every possible operation. Let the result of this above operation be X.
  2. Now, perform all possible operations on X and the next element of the array and so on.
  3. Repeat all the above steps until all the possible combinations of operations are performed.
  4. Now, if any combination of operations generates the result K, then print that combination.
  5. Otherwise, print “-1”.

Below is the implementation of the above approach: 


Output: 
2+0 => 2+2 => 4+0 => 4


Time Complexity: O(N!*4N)
Auxiliary Space: O(N)

Comment