In this HackerRank Arithmetic Expressions problem solution 5-year-old, Shinchan had just started learning mathematics. Meanwhile, one of his studious classmates, Kazama, had already written a basic calculator which supports only three operations on integers: multiplication (x), addition (+), and subtraction (-). Since he had just learned about these operations, he didn't know about operator precedence, and so, in his calculator, all operators had the same precedence and were left-associative.

As always, Shinchan started to irritate him with his silly questions. He gave Kazama a list of N integers and asked him to insert one of the above operators between each pair of consecutive integers such that the result obtained after feeding the resulting expression in Kazama's calculator is divisible by 101. At his core, Shinchan is actually a good guy, so he only gave lists of integers for which an answer exists.

Can you help Kazama create the required expression? If multiple solutions exist, print any one of them.

HackerRank Arithmetic Expressions problem solution


Problem solution in Python.

n=int(input())
elems=[int(x) for x in input().split(' ')]
ops=[None]*101
ops[elems[0]]=''
for e in elems[1:]:
  nops=[None]*101
  for (k,s) in enumerate(ops):
    if s==None:
      continue
    nops[(k+e)%101]=s+'+'
    nops[(k-e)%101]=s+'-'
    nops[(k*e)%101]=s+'*'
  ops=nops
r=str(elems[0])
for (k,s) in enumerate(ops[0]):
  r+=s+str(elems[k+1])
print(r)


Problem solution in Java.

import java.io.*;
import java.util.*;

public class Solution {

	static final int FACTOR = 101;
	
	static int N;
	static int[] A;
	static char[] B;
	
	static boolean printExpression(int res, int count) {
		int mod = res % FACTOR;

		if (count == N - 1) {
			if (mod == 0) {	
				return true;
			}
			return false;
		}
		
		if (printExpression(mod * A[count + 1], count + 1)) {
			B[count] = '*';
			return true;
		}
		
		if (printExpression(mod + A[count + 1], count + 1)) {
			B[count] = '+';
			return true;
		}
		
		int auxRes = mod - A[count + 1];
		if (printExpression(auxRes, count + 1)) {
			B[count] = '-';
			return true;
		}	
		
		return false;
	}

	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		
		
		N = sc.nextInt();
		A = new int[N];
		B = new char[N - 1];
		
		for (int i = 0; i < N; i++) {
			A[i] = sc.nextInt();
		}
		
		printExpression(A[0], 0);
		System.out.print(A[0]);
		for (int i = 0; i < N - 1; i++) {
			System.out.print(B[i] + "" + A[i + 1]);
		}
		System.out.println();
		
		sc.close();
	}
}


Problem solution in C++.

#include <iostream>

using namespace std;
int check=0;
void preform(int a[],int out [],int n,int starto,int starta,int res){
     if(res%101==0){
            cout<<out[0];
        for(int i = 1;i<2*starta;i+=2){
            if(out[i]==-1){
                cout<<'+';
            }else if(out[i]==-2){
                cout<<'-';
            }else if(out[i]==-3){
                cout<<'*';
            }
            cout<<out[i+1];

        }
        if(starta<n-1){
            cout<<'*';
        }

        for(int i = starta+1 ; i<n;i++){
                cout<<a[i];
            if(i!=n-1){
                cout<<'*';
            }
        }
        check=1;
        return;
    }
    if(starta==n-1){
        return;
    }
     if(check==0){
            out[starto]=-1;
            out[starto+1]=a[starta+1];
            int newres=res+a[starta+1];
            preform(a,out,n,starto+2,starta+1,newres);
        }
     if(check==0){
            out[starto]=-2;
            out[starto+1]=a[starta+1];
            int newres=res-a[starta+1];
            preform(a,out,n,starto+2,starta+1,newres);

        }
    if(check==0){
            out[starto]=-3;
            out[starto+1]=a[starta+1];
            int newres=res*a[starta+1];
            preform(a,out,n,starto+2,starta+1,newres);

    }

}
int main()
{
    int n;
    cin>>n;
    int arr[n];
    int  out[2*n-1];
    for(int  i = 0;i<n;i++){
        cin>>arr[i];
    }
    out[0]=arr[0];
    preform(arr,out,n,1,0,arr[0]);
    if(check==0){
        cout<<-1;
    }
    return 0;
}


Problem solution in C.

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

static int hash[10001][101];
static int hashminus[10001][101];
int ans=0;
char x[10001];

void solve(int curr,int n,int a[],int value){
    
    if(curr>n){
        if(value==0){
            ans=1;
        }
        return;
    }
    
    if(value<0){
        if(hashminus[curr][value*-1]==1)
            return;
        else{
            hashminus[curr][value*-1]=1;
            solve(curr+1,n,a,(value*a[curr])%101);
            if(ans==1){
                x[curr-2]='*';
                return;
            }
            solve(curr+1,n,a,(value+a[curr])%101);
            if(ans==1){
                x[curr-2]='+';
                return;
            }
            solve(curr+1,n,a,(value-a[curr])%101);
            if(ans==1){
                x[curr-2]='-';
                return;
            }
        }
    }
    else{
        if(hash[curr][value]==1)
            return;
        else{
            hash[curr][value]=1;
            solve(curr+1,n,a,(value*a[curr])%101);
            if(ans==1){
                x[curr-2]='*';
                return;
            }
            solve(curr+1,n,a,(value+a[curr])%101);
            if(ans==1){
                x[curr-2]='+';
                return;
            }
            solve(curr+1,n,a,(value-a[curr])%101);
            if(ans==1){
                x[curr-2]='-';
                return;
            }
        }
    }
}
int main() {

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    int i,k,j;
    int a[10001],n;
    scanf("%d",&n);   
    for(i=1;i<=n;i++){
        scanf("%d",&a[i]);
        a[i]%=101;   
    }
    solve(2,n,a,a[1]);
    printf("%d",a[1]);
    for(i=0;i<n-1;i++){
        printf("%c%d",x[i],a[i+2]);
    }
    return 0;
}