Count of ordered pairs (i, j) such that arr[i] and arr[j] concatenates to X

Given an array arr[] of size N and an integer X, the task is to find the number of ordered pairs (i, j) such that i != j and X is the concatenation of the numbers arr[i] and arr[j]Â
Examples:
Input: N = 4, arr[] = {1, 212, 12, 12}, X = 1212
Output: 3
Explanation: X = 1212 can be obtained by concatenating:
- numbers[0] = 1 with numbers[1] = 212
- numbers[2] = 12 with numbers[3] = 12
- numbers[3] = 12 with numbers[2] = 12
- Therefore, number of possible ordered pairs are 3
Input: N = 3, arr[] = {11, 11, 110}, X = 11011
Output: 2
Approach: Â The task can be solved using a hashmap Follow the below steps to solve the problem
- Store the lengths of all the numbers in a vector.
- Iterate over the given number array and check if X can be obtained from the number. If so increase the count to check with how many numbers does the current number can form a pair.
- Increase the value of the current number in the map.
- Clear the map and repeat the same steps on the given number array from the back.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to find the number of possible// ordered pairslong long countPairs(int n, int x, vector<int> v){    int power[10]        = { 1, 10, 100,            1000, 10000, 100000,            1000000, 10000000,            100000000,            1000000000 };Â
    // Stores the count of digits of each number    vector<int> len;    long long count = 0;    for (int i = 0; i < n; i++)        len.push_back(log10(v[i]) + 1);Â
    unordered_map<int, int> mp;    mp[v[0]]++;Â
    // Iterating from the start    for (int i = 1; i < n; i++) {        if (x % power[len[i]] == v[i])            count += mp[x / power[len[i]]];cout<<"count = "<<count<<endl;        mp[v[i]]++;    }Â
    mp.clear();    mp[v[n - 1]]++;Â
    // Iterating from the end    for (int i = n - 2; i >= 0; i--) {        if (x % power[len[i]] == v[i])            count += mp[x / power[len[i]]];cout<<"c = "<<count<<endl;        mp[v[i]]++;    }    return count;}Â
// Driver Codeint main(){Â Â Â Â int N = 4;Â Â Â Â int X = 1212;Â Â Â Â vector<int> numbers = { 1, 212, 12, 12 };Â Â Â Â long long ans = countPairs(N, X, numbers);Â Â Â Â cout << ans << endl;Â Â Â Â return 0;} |
Java
// Java program for the above approachimport java.util.*;class GFG {Â
  // Function to find the number of possible  // ordered pairs  static long countPairs(int n, int x, int[] v) {    int power[] = { 1, 10, 100, 1000, 10000, 100000,                    1000000, 10000000, 100000000, 1000000000 };Â
    // Stores the count of digits of each number    Vector<Integer> len = new Vector<Integer>();    long count = 0;    for (int i = 0; i < n; i++)      len.add((int) (Math.log10(v[i]) + 1));Â
    HashMap<Integer, Integer> mp = new HashMap<Integer, Integer>();    if (mp.containsKey(v[0])) {      mp.put(v[0], mp.get(v[0]) + 1);    } else {      mp.put(v[0], 1);    }Â
    // Iterating from the start    for (int i = 1; i < n; i++) {      if (x % power[len.get(i)] == v[i]&&mp.containsKey(x / power[len.get(i)]))        count += mp.get(x / power[len.get(i)]);      System.out.println("count = " + count);      if (mp.containsKey(v[i])) {        mp.put(v[i], mp.get(v[i]) + 1);      } else {        mp.put(v[i], 1);      }    }Â
    mp.clear();    if (mp.containsKey(v[n - 1])) {      mp.put(v[n - 1], mp.get(v[n - 1]) + 1);    } else {      mp.put(v[n - 1], 1);    }Â
    // Iterating from the end    for (int i = n - 2; i >= 0; i--) {      if (x % power[len.get(i)] == v[i]&&mp.containsKey(x / power[len.get(i)]))        count += mp.get(x / power[len.get(i)]);      System.out.println("c = " + count);      if (mp.containsKey(v[i])) {        mp.put(v[i], mp.get(v[i]) + 1);      } else {        mp.put(v[i], 1);      }    }    return count;  }Â
  // Driver Code  public static void main(String[] args) {    int N = 4;    int X = 1212;    int[] numbers = { 1, 212, 12, 12 };    long ans = countPairs(N, X, numbers);    System.out.print(ans + "\n");  }}Â
// This code is contributed by shikhasingrajput |
Python3
# Python 3 program for the above approachfrom collections import defaultdictimport mathÂ
# Function to find the number of possible# ordered pairsdef countPairs(n, x, v):Â
    power = [1, 10, 100,             1000, 10000, 100000,             1000000, 10000000,             100000000,             1000000000]Â
    # Stores the count of digits of each number    length = []    count = 0    for i in range(n):        length.append(int(math.log10(v[i])) + 1)Â
    mp = defaultdict(int)    mp[v[0]] += 1Â
    # Iterating from the start    for i in range(1, n):        if (x % power[length[i]] == v[i]):            count += mp[x // power[length[i]]]        mp[v[i]] += 1Â
    mp.clear()    mp[v[n - 1]] += 1Â
    # Iterating from the end    for i in range(n - 2, -1, -1):        if (x % power[length[i]] == v[i]):            count += mp[x // power[length[i]]]Â
        mp[v[i]] += 1Â
    return countÂ
# Driver Codeif __name__ == "__main__":Â
    N = 4    X = 1212    numbers = [1, 212, 12, 12]    ans = countPairs(N, X, numbers)    print(ans)Â
    # This code is contributed by ukasp. |
C#
// C# program to implement above approachusing System;using System.Collections;using System.Collections.Generic;Â
class GFG{Â
  // Function to find the number of possible  // ordered pairs  static long countPairs(int n, int x, int[] v) {    int[] power = new int[]{ 1, 10, 100, 1000, 10000, 100000,                            1000000, 10000000, 100000000, 1000000000 };Â
    // Stores the count of digits of each number    List<int> len = new List<int>();    long count = 0;    for (int i = 0 ; i < n ; i++){      len.Add((int)(Math.Log10(v[i]) + 1));    }Â
    Dictionary<int, int> mp = new Dictionary<int, int>();    if (mp.ContainsKey(v[0])) {      mp[v[0]]+=1;    }else {      mp.Add(v[0], 1);    }Â
    // Iterating from the start    for (int i = 1; i < n; i++) {      if (x % power[len[i]] == v[i] && mp.ContainsKey(x / power[len[i]])){        count += mp[x / power[len[i]]];      }      // Console.WriteLine("count = " + count);      if (mp.ContainsKey(v[i])) {        mp[v[i]]+=1;      } else {        mp.Add(v[i], 1);      }    }Â
    mp.Clear();    if (mp.ContainsKey(v[n - 1])) {      mp[v[n - 1]] += 1;    } else {      mp.Add(v[n - 1], 1);    }Â
    // Iterating from the end    for (int i = n - 2; i >= 0; i--) {      if (x % power[len[i]] == v[i] && mp.ContainsKey(x / power[len[i]])){        count += mp[x / power[len[i]]];      }      // Console.WriteLine("c = " + count);      if (mp.ContainsKey(v[i])) {        mp[v[i]] += 1;      } else {        mp.Add(v[i], 1);      }    }    return count;  }Â
  public static void Main(string[] args){Â
    int N = 4;    int X = 1212;    int[] numbers = new int[]{ 1, 212, 12, 12 };    long ans = countPairs(N, X, numbers);    Console.WriteLine(ans);Â
  }}Â
// This code is contributed by subhamgoyal2014. |
Javascript
<script>Â Â Â Â Â Â Â Â // JavaScript code for the above approach Â
        // Function to find the number of possible        // ordered pairs        function countPairs(n, x, v) {            let power = [1, 10, 100,                    1000, 10000, 100000,                    1000000, 10000000,                    100000000,                    1000000000];Â
            // Stores the count of digits of each number            let len = [];            let count = 0;            for (let i = 0; i < n; i++)                len.push(Math.floor(Math.log10(v[i])) + 1);Â
            let mp = new Map();            mp.set(v[0], 1);Â
            // Iterating from the start            for (let i = 1; i < n; i++) {                if (x % power[len[i]] == v[i] && mp.has(Math.floor(x / power[len[i]])))                    count += mp.get(Math.floor(x / power[len[i]]));Â
                if (mp.has(v[i])) {                    mp.set(v[i], mp.get(v[i]) + 1)                }                else {                    mp.set(v[i], 1)                }            }Â
            mp = new Map();            mp.set(v[n - 1], 1);Â
            // Iterating from the end            for (let i = n - 2; i >= 0; i--) {                if (x % power[len[i]] == v[i] && mp.has(Math.floor(x / power[len[i]])))                    count += mp.get(Math.floor(x / power[len[i]]));Â
                if (mp.has(v[i])) {                    mp.set(v[i], mp.get(v[i]) + 1)                }                else {                    mp.set(v[i], 1)                }            }            return count;        }Â
        // Driver CodeÂ
        let N = 4;        let X = 1212;        let numbers = [1, 212, 12, 12];        let ans = countPairs(N, X, numbers);        document.write(ans + '<br>')Â
         // This code is contributed by Potta Lokesh    </script> |
Â
Â
Output
3
Â
Time complexity: O(N)
Auxiliary Space: O(N)
Â
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



