Wednesday, July 3, 2024
HomeData ModellingData Structure & AlgorithmCount of ordered pairs (i, j) such that arr and arr concatenates...

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 pairs
long 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 Code
int 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 approach
import 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 approach
from collections import defaultdict
import math
 
# Function to find the number of possible
# ordered pairs
def 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 Code
if __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 approach
using 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 neveropen!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments