Given an array of integers arr[], A pairs (i, j) is valid, which follows the below two conditions:
- Concatenation of integer at i’th and j’th index have even number of digits (Even digit Concatenation)
- Sum of digits in the first half = sum of digits in the second half (Balanced Digit Sum)
The task is to count all such valid pairs in the given array with Balanced Digit Sums and Even-Digit Concatenation.
Example:
Input: arr = {1,1,1} Output: 9
Input: arr[] = {“2”, “22”, “222”, “2222”, “22222”} Output: 13
Approach:
The intuition behind the solution lies in the observation that a valid pair must satisfy two conditions:
- Concatenation has even number of digits: This implies that the length of the string formed by concatenating the two strings must be even.
- Sum of digits in first half = Sum of digits in second half: This means that the sum of digits in the first half of the concatenated string must be equal to the sum of digits in the second half.
Steps-by-step approach:
- Create an array sum to store the cumulative sum of digits.
- Create a 2D array str to store the strings.
- Initialize a map mp to store the number of occurrences of each pair of values.
- Calculate Cumulative Sum and Populate Map
- Loop through each element (i):
- Get the string from the strings array.
- Loop through each character in the string and calculate the sum of its digits.
- Loop through each character in the string and calculate the cumulative sum of digits.
- For each character in the string, create a unique key based on the sum and position. Update the count for this key in the map.
- Count Valid Pairs
- Initialize ans as 0.
- Loop through each element (i) again:
- Get the string from the strings array.
- For each character in the string, check for valid pairs using the sum and length. Update the answer with the count from the map.
- Print the final result, which represents the total number of valid pairs.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 200010;
ll sum[N];
char str[N][10];
ll solve( int n,string strings[])
{
map<pair<ll, ll>, int > mp;
for (ll i = 1; i <= n; ++i) {
string str_i = strings[i - 1];
ll len = str_i.length();
ll ssum = 0;
for (ll j = 0; j < len; ++j) {
ssum += str_i[j] - '0' ;
}
for (ll j = 0; j < len; ++j) {
sum[i] += str_i[j] - '0' ;
pair<ll, ll> key
= { 2 * sum[i] - ssum, 2 * (j + 1) - len };
mp[key]++;
}
}
ll ans = 0;
for (ll i = 1; i <= n; ++i) {
string str_i = strings[i - 1];
ll len = str_i.length();
ans += mp[{ sum[i], len }] + mp[{ -sum[i], -len }];
}
return ans;
}
int main()
{
ll n = 5;
string strings[]
= { "2" , "22" , "222" , "2222" , "22222" };
cout << solve(n,strings) << endl;
return 0;
}
|
Java
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;
public class Main {
private static final int N = 200010 ;
private static long [] sum = new long [N];
private static long solve( int n, String[] strings)
{
Map<AbstractMap.SimpleEntry<Long, Long>, Integer> mp
= new HashMap<>();
for ( long i = 1 ; i <= n; ++i) {
String str_i = strings[( int )(i - 1 )];
int len = str_i.length();
long ssum = 0 ;
for ( int j = 0 ; j < len; ++j) {
ssum += str_i.charAt(j) - '0' ;
}
for ( int j = 0 ; j < len; ++j) {
sum[( int )i] += str_i.charAt(j) - '0' ;
AbstractMap.SimpleEntry<Long, Long> key
= new AbstractMap.SimpleEntry<>(
2 * sum[( int )i] - ssum,
2 * (j + 1L) - len);
mp.put(key, mp.getOrDefault(key, 0 ) + 1 );
}
}
long ans = 0 ;
for ( long i = 1 ; i <= n; ++i) {
String str_i = strings[( int )(i - 1 )];
int len = str_i.length();
ans += mp.getOrDefault(
new AbstractMap.SimpleEntry<>(
sum[( int )i], ( long )len),
0 )
+ mp.getOrDefault(
new AbstractMap.SimpleEntry<>(
-sum[( int )i], ( long )-len),
0 );
}
return ans;
}
public static void main(String[] args)
{
int n = 5 ;
String[] strings
= { "2" , "22" , "222" , "2222" , "22222" };
System.out.println(solve(n, strings));
}
}
|
Python3
N = 200010
sums = [ 0 ] * N
def solve(n, strings):
mp = {}
for i in range ( 1 , n + 1 ):
str_i = strings[i - 1 ]
length = len (str_i)
ssum = sum ( int (digit) for digit in str_i)
for j in range (length):
sums[i] + = int (str_i[j])
key = ( 2 * sums[i] - ssum, 2 * (j + 1 ) - length)
mp[key] = mp.get(key, 0 ) + 1
ans = 0
for i in range ( 1 , n + 1 ):
str_i = strings[i - 1 ]
length = len (str_i)
ans + = mp.get((sums[i], length), 0 ) + mp.get(( - sums[i], - length), 0 )
return ans
if __name__ = = "__main__" :
n = 5
strings = [ "2" , "22" , "222" , "2222" , "22222" ]
print (solve(n, strings))
|
C#
using System;
using System.Collections.Generic;
class Program
{
const int N = 200010;
static long [] sum = new long [N];
static long Solve( int n, string [] strings)
{
Dictionary< long , int > positiveKeys = new Dictionary< long , int >();
Dictionary< long , int > negativeKeys = new Dictionary< long , int >();
for ( long i = 1; i <= n; ++i)
{
string str_i = strings[i - 1];
long len = str_i.Length;
long ssum = 0;
for ( long j = 0; j < len; ++j)
{
ssum += str_i[( int )j] - '0' ;
}
for ( long j = 0; j < len; ++j)
{
sum[i] += str_i[( int )j] - '0' ;
long positiveKey = 2 * sum[i] - ssum;
long negativeKey = 2 * (j + 1) - len;
if (positiveKeys.ContainsKey(positiveKey))
positiveKeys[positiveKey]++;
else
positiveKeys[positiveKey] = 1;
if (negativeKeys.ContainsKey(negativeKey))
negativeKeys[negativeKey]++;
else
negativeKeys[negativeKey] = 1;
}
}
long ans = 0;
for ( long i = 1; i <= n; ++i)
{
string str_i = strings[i - 1];
long len = str_i.Length;
long positiveKey = sum[i];
long negativeKey = -len;
if (positiveKeys.ContainsKey(positiveKey))
ans += positiveKeys[positiveKey];
if (negativeKeys.ContainsKey(negativeKey))
ans += negativeKeys[negativeKey];
}
return ans;
}
static void Main()
{
long n = 5;
string [] strings = { "2" , "22" , "222" , "2222" , "22222" };
Console.WriteLine(Solve(( int )n, strings));
}
}
|
Javascript
let sum = new Array(200010).fill(0);
function solve(n, strings) {
let mp = new Map();
for (let i = 1; i <= n; ++i) {
let str_i = strings[i - 1];
let len = str_i.length;
let ssum = 0;
for (let j = 0; j < len; ++j) {
ssum += parseInt(str_i[j]);
}
for (let j = 0; j < len; ++j) {
sum[i] += parseInt(str_i[j]);
let key = `${2 * sum[i] - ssum},${2 * (j + 1) - len}`;
if (mp.has(key)) {
mp.set(key, mp.get(key) + 1);
} else {
mp.set(key, 1);
}
}
}
let ans = 0;
for (let i = 1; i <= n; ++i) {
let str_i = strings[i - 1];
let len = str_i.length;
ans += (mp.get(`${sum[i]},${len}`) || 0) + (mp.get(`${-sum[i]},${-len}`) || 0);
}
return ans;
}
let n = 5;
let strings = [ "2" , "22" , "222" , "2222" , "22222" ];
console.log(solve(n, strings));
|
Time Complexity: O(n*m*log(n*m)), where n is the number of elements (strings) in the array and m is the maximum length of any string. Auxiliary Space: O(n*m)
|