Encrypt given Array in single digit using inverted Pascal Triangle
Last Updated :
23 Jul, 2025
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;
}
Java
// Java code for the above approach:
import java.io.*;
import java.util.*;
class GFG
{
// Recursive function to find the encryption
public static String
digitEncrypt(ArrayList<Integer> numbers)
{
int N = numbers.size();
// If the value of N is 2
if (N == 2) {
if (numbers.get(0) == 0 && numbers.get(1) == 0)
return "00";
else if (numbers.get(0) == 0)
return "0"
+ Integer.toString(numbers.get(1));
else
return Integer.toString(numbers.get(0))
+ Integer.toString(numbers.get(1));
}
for (int i = 0; i < N - 1; i++)
numbers.set(
i, ((numbers.get(i) + numbers.get(i + 1))
% 10));
numbers.remove(numbers.size() - 1);
return digitEncrypt(numbers);
}
// Driver Code
public static void main(String[] args)
{
ArrayList<Integer> numbers = new ArrayList<Integer>(
Arrays.asList(4, 5, 6, 7));
// Function call
System.out.print(digitEncrypt(numbers));
}
}
// This code is contributed by Rohit Pradhan
Python3
# python3 code to implement the approach
# Recursive function to find the encryption
def digitEncrypt(numbers) :
N = len(numbers)
# If the value of N is 2
if N == 2 :
if numbers[0] == 0 and numbers[1] == 0 :
return "00"
elif numbers[0] == 0:
return "0" + str((numbers[1]))
return str(numbers[0])+ str(numbers[1])
for i in range(0,N-1) :
numbers[i] = (numbers[i]+ numbers[i + 1])% 10
numbers.pop()
return digitEncrypt(numbers)
# Driver code
if __name__ == "__main__":
numbers = [ 4, 5, 6, 7 ]
# Function call
print(digitEncrypt(numbers))
# This code is contributed by jana_sayantan.
C#
// C# code for the above approach:
using System;
using System.Collections.Generic;
class GFG {
// Recursive function to find the encryption
public static string digitEncrypt(List<int> numbers)
{
int N = numbers.Count;
// 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" + Convert.ToString(numbers[1]);
else
return Convert.ToString(numbers[0])
+ Convert.ToString(numbers[1]);
}
for (int i = 0; i < N - 1; i++)
numbers[i] = (numbers[i] + numbers[i + 1]) % 10;
numbers.RemoveAt(numbers.Count - 1);
return digitEncrypt(numbers);
}
// Driver Code
public static void Main(string[] args)
{
List<int> numbers
= new List<int>(new int[] { 4, 5, 6, 7 });
// Function call
Console.Write(digitEncrypt(numbers));
}
}
// This code is contributed by phasing17
JavaScript
<script>
// JavaScript code for the above approach:
// Recursive function to find the encryption
function digitEncrypt(numbers)
{
var N = numbers.length;
var 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" + (numbers[1]);
return to_string(numbers[0])
+ to_string(numbers[1]);
}
for (var i = 0; i < N - 1; i++)
numbers[i] = (numbers[i]
+ numbers[i + 1])
% 10;
numbers.pop();
return digitEncrypt(numbers);
}
// Drivers code
var numbers = [ 4, 5, 6, 7 ];
// Function call
document.write(digitEncrypt(numbers));
// This code is contributed by phasing17.
</script>
Time Complexity: O(N2)
Auxiliary Space: O(N)
Approach 2: Using Queue ( just read the code you will get the approach by comments)
C++
#include <bits/stdc++.h>
using namespace std;
// iterative function to find the encryption
string digitEncrypt(vector<int> numbers){
queue<int>q;
//push all elements of vector number to queue and traverse queue until we get the final result
for(auto x: numbers){
q.push(x);
}
// when queue has only 2 elements left then stop the cycle
while(q.size() != 2){
int n = q.size()-1;
while(n--){
int a= q.front(); // first element
q.pop();
int b = q.front(); // 2nd element
int sum = (a%10) + (b%10); // if 'a' or 'b' greater than 10 then just '%10' to get make is a single digit number
sum = sum%10; // same with sum to make it a single digit number
q.push(sum); // push that sum in queue for the another traversal
}
q.pop();
}
// now made from both the digit by converting them into string
// we convert them into string because when a=0 we cannot do ans = a*10 + b
// thats why we convert them into string and then add to them into our answer string
int a= q.front();
q.pop();
int b = q.front();
string ans = "";
ans+=to_string(a);
ans+=to_string(b);
return ans;
}
int main()
{
vector<int> numbers = { 4, 5, 6, 7 };
cout << digitEncrypt(numbers);
return 0;
}
Java
// Java code for the above approach:
import java.io.*;
import java.util.*;
class GFG {
// Iterative function to find the encryption
public static String
digitEncrypt(ArrayList<Integer> numbers)
{
Queue<Integer> q = new LinkedList<>();
// push all elements of vector number to queue and
// traverse queue until we get the final result
for (Integer x : numbers) {
q.add(x);
}
// when queue has only 2 elements left then stop the
// cycle
while (q.size() != 2) {
int n = q.size() - 1;
while (n > 0) {
// first element
int a = q.peek();
q.remove();
// 2nd element
int b = q.peek();
// if 'a' or 'b' greater than 10 then just
// '%10' to get make is a single digit
// number
int sum = (a % 10) + (b % 10);
// same with sum to make it a single digit
// number
sum = sum % 10;
// push that sum in queue for the another
// traversal
q.add(sum);
n--;
}
q.remove();
}
// now made from both the digit by converting them
// into string we convert them into string because
// when a=0 we cannot do ans = a*10 + b thats why we
// convert them into string and then add to them
// into our answer string
int a = q.peek();
q.remove();
int b = q.peek();
String ans = String.valueOf(a);
ans += String.valueOf(b);
return ans;
}
// Driver Code
public static void main(String[] args)
{
ArrayList<Integer> numbers = new ArrayList<Integer>(
Arrays.asList(4, 5, 6, 7, 8, 9));
// Function call
System.out.print(digitEncrypt(numbers));
}
}
// This code is contributed by shubhamrajput6156
Python3
# Python3 code for the above approach:
# function to find the encryption
def digitEncrypt(numbers):
q = []
# push all elements of numbers list to queue
for x in numbers:
q.append(x)
# traverse queue until we get the final result
while len(q) != 2:
n = len(q)-1
while n > 0:
a = q.pop(0) # first element
b = q[0] # 2nd element
sum = (a % 10) + (b % 10) # if 'a' or 'b' greater than 10 then just '%10' to get make is a single digit number
sum = sum % 10 # same with sum to make it a single digit number
q.append(sum) # push that sum in queue for the another traversal
n -= 1
q.pop(0)
# now made from both the digit by
# converting them into string
# we convert them into string because
# when a=0 we cannot do ans = a*10 + b
# thats why we convert them into string
# and then add to them into our answer string
a = q.pop(0)
b = q[0]
ans = str(a) + str(b)
return ans
# Driver Code
if __name__ == "__main__":
# Input array
numbers = [4, 5, 6, 7]
# Function Call
print(digitEncrypt(numbers))
C#
using System;
using System.Collections.Generic;
public class GFG {
// Iterative function to find the encryption
public static string DigitEncrypt(List<int> numbers) {
Queue<int> q = new Queue<int>();
// Push all elements of the list to the queue and
// traverse queue until we get the final result
foreach (int x in numbers) {
q.Enqueue(x);
}
// When queue has only 2 elements left then stop the cycle
while (q.Count != 2) {
int n = q.Count - 1;
while (n > 0) {
// First element
int a = q.Peek();
q.Dequeue();
// Second element
int b = q.Peek();
// If 'a' or 'b' greater than 10 then just
// '%10' to get make it a single digit number
int sum = (a % 10) + (b % 10);
// Same with sum to make it a single digit
// number
sum = sum % 10;
// Push that sum in queue for the another
// traversal
q.Enqueue(sum);
n--;
}
q.Dequeue();
}
// Now made from both the digit by converting them
// into string we convert them into string because
// when a=0 we cannot do ans = a*10 + b thats why we
// convert them into string and then add to them
// into our answer string
int a1 = q.Peek();
q.Dequeue();
int b1 = q.Peek();
string ans = a1.ToString() + b1.ToString();
return ans;
}
// Driver Code
public static void Main(string[] args) {
List<int> numbers = new List<int>(new int[] {4, 5, 6, 7, 8, 9});
// Function call
Console.Write(DigitEncrypt(numbers));
}
}
JavaScript
// JavaScript code for the above approach:
function digitEncrypt(numbers) {
const q = [];
// push all elements of array 'numbers' to queue and
// traverse queue until we get the final result
for (let i = 0; i < numbers.length; i++) {
q.push(numbers[i]);
}
// when queue has only 2 elements left then stop the
// cycle
while (q.length !== 2) {
let n = q.length - 1;
while (n > 0) {
// first element
const a = q.shift();
// 2nd element
const b = q[0];
// if 'a' or 'b' greater than 10 then just
// '%10' to get make it a single digit number
const sum = (a % 10) + (b % 10);
// same with sum to make it a single digit number
const digitSum = sum % 10;
// push that digitSum in queue for the another
// traversal
q.push(digitSum);
n--;
}
q.shift();
}
// now made from both the digit by converting them
// into string we convert them into string because
// when a=0 we cannot do ans = a*10 + b thats why we
// convert them into string and then add to them
// into our answer string
const a = q.shift();
const b = q.shift();
let ans = a.toString();
ans += b.toString();
return ans;
}
// Driver Code
const numbers = [4, 5, 6, 7, 8, 9];
// Function call
console.log(digitEncrypt(numbers));
Time Complexity: O(N2)
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem