Header Ad

HackerRank Winning Lottery Ticket problem solution

In this HackerRank Winning Lottery Ticket problem solution, Your task is to find the number of winning pairs of distinct tickets, such that concatenation of their ticket IDs (in any order) makes for a winning scenario. Complete the function winningLotteryTicket which takes a string array of ticket IDs as input, and returns the number of winning pairs.

HackerRank Winning Lottery Ticket problem solution


Problem solution in Python.

n = int(input())
p = [input().strip() for _ in range(n)]

fullMask = 2**10-1
cntMask = [0 for _ in range(fullMask+1)]

for s in p:
    mask = 0
    for c in s:
        mask |= 1 << (ord(c) - ord('0'))
    cntMask[mask] += 1

res = 0
for i in range(fullMask+1):
    for j in range(i+1, fullMask+1):
        if i | j == fullMask:
            res += cntMask[i] * cntMask[j]

res += cntMask[fullMask] * (cntMask[fullMask]-1) / 2
print(int(res))


Problem solution in C++.

 
#include "bits/stdc++.h"
using namespace std;
const int N = 1e6 + 6;
int n;
int cnt[1 << 10];


void readInp() {
  ios_base :: sync_with_stdio(false);
  cin.tie(NULL);
  string x;
  cin >> n;
  for(int i = 1; i <= n; ++i) {
    cin >> x;
    int mask = 0;
    for(int j = 0; j < x.size(); ++j) mask |= (1 << (x[j] - '0'));
    ++cnt[mask];
  }
}

long long solve() {
   long long ans = 0;
   for(int m1 = 0; m1 <= 1023; ++m1) 
    for(int m2 = 0; m2 <= 1023; ++m2)
     if((m1 | m2) == 1023) 
        ans += m1 == m2 ? 1LL * cnt[m1] * (cnt[m1] - 1) : 1LL * cnt[m1] * cnt[m2];  
    return ans / 2LL;
}

void out(long long x) {
    cout << x << endl;
}

int main() {
    readInp();
    out(solve());
    return 0;
}


Post a Comment

0 Comments