Skip to content
Related Articles

Related Articles

Check if Triplet exist whose sum ends with digit K

View Discussion
Improve Article
Save Article
  • Last Updated : 13 Sep, 2022
View Discussion
Improve Article
Save Article

Given an array arr[] of size N, determine if there exist 3 distinct indices integers, such that their sum ends in digit K.

Examples:

Input: arr[] = {1, 2, 5, 3}, K = 0
Output: YES
Explanation: 2 + 3 + 5 = 10 i.e., end digit 0.

Input: arr[] = {3, 1, 8, 4}, K = 0
Output: NO

Approach:  To solve the problem follow the below idea:

Find all possible triplets of single digit and the ending digit of their sum and map the triplets to their corresponding end digit. Now for K check if there is any triplet in the array which is mapped to K.

Follow the steps mentioned below to implement the above idea:

  • Preprocess all the triplets within range 0-9 such that their sum results in end digit K and store them in a vector of map.
  • Store the frequency of the last digit of every element in another Map. 
  • Then, traverse the vector and check:
    • If frequencies of all elements in the map for any triplet is greater or equal to frequencies of the same element in the vector. 
      • So, print Yes. 
    • If no such triplet is found after traversing the vector, return No as the answer. 

Below is the implementation for the above approach:

C++




// C++ code to implement the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if there exist 3 inegers
// such that their sum result in end digit K
string solve(int arr[], int n, int K)
{
    map<int, int> Mp;
    vector<map<int, int> > VectorSum;
 
    // Preprocessing all the distinct indices
    // integers such that their resultant
    // sum has end digit K
    for (int i = 0; i < 10; i++)
        for (int j = 0; j < 10; j++)
            for (int k = 0; k < 10; k++) {
                if ((i + j + k) % 10 == K) {
                    map<int, int> temp;
                    temp[i] += 1;
                    temp[j] += 1;
                    temp[k] += 1;
                    VectorSum.push_back(temp);
                    temp.clear();
                }
            }
 
    // Count frequency of last digit of
    // each elements
    for (int i = 0; i < n; i++) {
        Mp[arr[i] % 10]++;
    }
 
    // Traverse in vetor to check the condition
    for (auto i : VectorSum) {
 
        // Initialize flag to 0
        bool flag = 0;
 
        // If the frequency of any elements
        // in map is less than frequency of
        // same element in vector for any
        // triplet then turn on flag
        for (auto j : i) {
            if (Mp[j.first] < j.second)
                flag = 1;
        }
 
        // If flag is off then it means
        // frequency of all elements in map
        // is greater or equal to frequency of
        // same element in vector for any
        // triplet So, print Yes
        if (flag == 0)
            return "YES";
    }
 
    // Else print No if any triplet not found
    // such that there sum result in end digit K
    return "NO";
}
 
// Driver Code
int main()
{
 
    int arr[] = { 1, 2, 5, 3 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 0;
 
    // Function Call
    cout << solve(arr, N, K);
 
    return 0;
}


Java




// Java code to implement the above approach
import java.util.*;
 
class GFG{
 
  // Function to check if there exist 3 inegers
  // such that their sum result in end digit K
  static String solve(int arr[], int n, int K)
  {
    HashMap<Integer,Integer> Mp = new HashMap<Integer,Integer>();
    Vector<HashMap<Integer,Integer> > VectorSum = new Vector<HashMap<Integer,Integer> >();
 
    // Preprocessing all the distinct indices
    // integers such that their resultant
    // sum has end digit K
    for (int i = 0; i < 10; i++)
      for (int j = 0; j < 10; j++)
        for (int k = 0; k < 10; k++) {
          if ((i + j + k) % 10 == K) {
            HashMap<Integer,Integer> temp = new HashMap<Integer,Integer>();
            if(temp.containsKey(i))
              temp.put(i, temp.get(i)+1);
            else
              temp.put(i, 1);
            if(temp.containsKey(j))
              temp.put(j, temp.get(j)+1);
            else
              temp.put(j, 1);
            if(temp.containsKey(k))
              temp.put(k, temp.get(k)+1);
            else
              temp.put(k, 1);
            VectorSum.add(temp);
            temp.clear();
          }
        }
 
    // Count frequency of last digit of
    // each elements
    for (int i = 0; i < n; i++) {
      if(Mp.containsKey(arr[i] % 10))
        Mp.put(arr[i] % 10, Mp.get(arr[i] % 10)+1);
      else
        Mp.put(arr[i] % 10, 1);
    }
 
    // Traverse in vetor to check the condition
    for (HashMap<Integer,Integer> i : VectorSum) {
 
      // Initialize flag to 0
      boolean flag = false;
 
      // If the frequency of any elements
      // in map is less than frequency of
      // same element in vector for any
      // triplet then turn on flag
      for (Map.Entry<Integer,Integer> j : i.entrySet()) {
        if (Mp.get(j.getKey()) < j.getValue())
          flag = true;
      }
 
      // If flag is off then it means
      // frequency of all elements in map
      // is greater or equal to frequency of
      // same element in vector for any
      // triplet So, print Yes
      if (flag == false)
        return "YES";
    }
 
    // Else print No if any triplet not found
    // such that there sum result in end digit K
    return "NO";
  }
 
  // Driver Code
  public static void main(String[] args)
  {
 
    int arr[] = { 1, 2, 5, 3 };
    int N = arr.length;
    int K = 0;
 
    // Function Call
    System.out.print(solve(arr, N, K));
  }
}
 
// This code contributed by shikhasingrajput


Python3




# python3 code to implement the above approach
 
# Function to check if there exist 3 inegers
# such that their sum result in end digit K
def solve(arr, n, K):
 
    Mp = {}
    VectorSum = []
 
    # Preprocessing all the distinct indices
    # integers such that their resultant
    # sum has end digit K
    temp = {}
    for i in range(0, 10):
        for j in range(0, 10):
            for k in range(0, 10):
                if ((i + j + k) % 10 == K):
                    temp[i] = temp[i] + 1 if i in temp else 1
                    temp[j] = temp[j] + 1 if j in temp else 1
                    temp[k] = temp[k] + 1 if k in temp else 1
                    VectorSum.append(temp)
                    temp = {}
 
    # Count frequency of last digit of
    # each elements
    for i in range(0, n):
        Mp[arr[i] % 10] = Mp[arr[i] % 10] + 1 if arr[i] % 10 in Mp else 1
 
    # Traverse in vetor to check the condition
    for i in VectorSum:
 
        # Initialize flag to 0
        flag = 0
 
        # If the frequency of any elements
        # in map is less than frequency of
        # same element in vector for any
        # triplet then turn on flag
        for j in i:
            if (j in Mp and Mp[j] < i[j]):
                flag = 1
            if not (j in Mp):
                flag = 1
 
        # If flag is off then it means
        # frequency of all elements in map
        # is greater or equal to frequency of
        # same element in vector for any
        # triplet So, print Yes
        if (flag == 0):
            return "YES"
 
    # Else print No if any triplet not found
    # such that there sum result in end digit K
    return "NO"
 
# Driver Code
if __name__ == "__main__":
 
    arr = [1, 2, 5, 3]
    N = len(arr)
    K = 0
 
    # Function Call
    print(solve(arr, N, K))
 
    # This code is contributed by rakeshsahni


Output

YES

Time Complexity: O( Max( N, 1000) )
Auxiliary Space: O(N)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!