The Wayback Machine - https://web.archive.org/web/20220410032447/https://www.geeksforgeeks.org/encrypt-given-array-in-single-digit-using-inverted-pascal-triangle/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Encrypt given Array in single digit using inverted Pascal Triangle

  • Last Updated : 08 Apr, 2022

Given an array arr[] of length N (N > 1)containing positive integers, the task is to encrypt the numbers of the array into a single digit using the inverted Pascal triangle as follows.

  • From the starting of the array find the sum of two adjacent elements.
  • Replace the sum with only the digit at the unit position of the sum.
  • Replace all the array elements with the values formed in this way and continue until there are only two elements left.
  • The last two elements are concatenated together.

Examples:

Input: arr[] = {4, 5, 6, 7}
Output: 04
Explanation:

Pascal’s encryption of [4, 5, 6, 7]

Input: arr[] = {1, 2, 3}
Output: 35
Explanation:

Pascal’s encryption of [1, 2, 3]

Input: arr[] = {14, 5}
Output: 145
Explanation: As there were two elements they are appended together

 

Approach: This problem can be solved using recursion based on the following idea:

Calculate the sum of all ith with (i-1)th element and mod by 10 to get least significant digit for next operation until the whole container becomes of length 2.

Follow the steps to solve the problem:

  • Use a recursive function and do the following:
    • Traverse numbers to calculate sum of adjacent elements and mod with 10 to get single least significant digit as numbers[i]=(numbers[i]+numbers[i+1])%10
    • Delete the last element from the array, as one element will be reduced after each operation.
    • Continue this procedure until only 2 elements are left.

Below is the implementation of the above approach:

C++14




// C++ code for the above approach:
  
#include <bits/stdc++.h>
using namespace std;
  
// Recursive function to find the encryption
string digitEncrypt(vector<int>& numbers)
{
    int N = numbers.size();
    string ans;
  
    // If the value of N is 2
    if (N == 2) {
        if (numbers[0] == 0 && numbers[1] == 0)
            return "00";
        else if (numbers[0] == 0)
            return "0" + to_string(numbers[1]);
        return to_string(numbers[0])
               + to_string(numbers[1]);
    }
  
    for (int i = 0; i < N - 1; i++)
        numbers[i] = (numbers[i]
                      + numbers[i + 1])
                     % 10;
  
    numbers.pop_back();
  
    return digitEncrypt(numbers);
}
  
// Drivers code
int main()
{
    vector<int> numbers = { 4, 5, 6, 7 };
  
    // Function call
    cout << digitEncrypt(numbers);
    return 0;
}
Output
04

Time Complexity: O(N2)
Auxiliary Space: O(N)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!